Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find() or children() to search top-level children only for a style?

Tags:

jquery

I'd like to find if a child element exists which has either of two class styles applied. My code looks like this:

var listOfMatchedResults = $("#parentList").find(".myStyle1, .myStyle2");

My styles are defined like this:

.parent li, .myStyle0 {
}

.parent li.myStyle1 {
}

.parent li.myStyle2 {
}

I don't need to traverse more than one level deeper than the children level, like:

<ul id='parentList'>
    <li><p>foo</p><p>grok</p></li>
    <li class='myStyle2'><p>Here</p><p>I am!</p></li>
    <li><p>foo</p><p>grok</p></li>
</ul>

I'm not clear as to what find() is doing, is it going into each of the paragraph elements too? I just need it to traverse the top-level children - is there a way to specify that?

Thank you

like image 237
user291701 Avatar asked Jun 15 '10 13:06

user291701


People also ask

What is the difference between find and children methods of jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do I select a specific child in Javascript?

Approach 1: Select an element whose child element is going to be selected. Use . children property to get access of all the children of the element. Select the particular child based on the index.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.

What are child elements in HTML?

A child is an element that is directly below and connected to an element in the document tree.


1 Answers

I'm not clear as to what find() is doing, is it going into each of the paragraph elements too?

yes it does

I just need it to traverse the top-level children - is there a way to specify that?

yes, use .children()

From API Doc:

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

like image 89
jAndy Avatar answered Oct 19 '22 06:10

jAndy