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.

jsfiddle

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

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -