Find an element when parsing HTML with jQuery no matter where it is -
how access element when parsing html jquery no matter is?
more specifically, why equals 0
:
$('<div class="messages"><p>just test.</p></div><div class="messages">another test</div>') .find('div.messages').length == 0
where equals 1
should:
$('<div><div class="messages"><p>just test.</p></div></div>') .find('div.messages').length == 1
okay, can wrap every time, have to?
the problem can't know if element i'm looking root element or not. in given html document need find no matter is.
you need use filter(), filter root elements, .find() search descendant elements of root set find matches.
snippet.log($('<div class="messages"><p>just test.</p></div>').filter('div.messages').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
if have 1 element @ root, no need jquery()
returns root element
snippet.log($('<div class="messages"><p>just test.</p></div>').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Comments
Post a Comment