Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery first child of "this"

I'm trying to pass "this" from a clicked span to a jQuery function that can then execute jQuery on that clicked element's first child. Can't seem to get it right...

<p onclick="toggleSection($(this));"><span class="redClass"></span></p> 

Javascript:

function toggleSection(element) {   element.toggleClass("redClass"); } 

How do I reference the :first-child of element?

like image 807
macca1 Avatar asked Feb 16 '10 19:02

macca1


People also ask

How to get first child of element jQuery?

The :first-child selector selects all elements that are the first child of their parent. Tip: Use the :last-child selector to select elements that are the last child of their parent.

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 is the difference between first child and first-of-type?

The :first-child: The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the <! DOCTYPE> must be declared for IE8 and earlier versions. The :first-of-type: The :first-of-type Selector is used to targeting the first child of every element of it's parent.


2 Answers

If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:

element.find(">:first-child").toggleClass("redClass"); 

Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). He also points out that you could just as well use the children() function, which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...):

element.children(":first").toggleClass("redClass"); 
like image 145
Shog9 Avatar answered Sep 26 '22 00:09

Shog9


Use the children function with the :first selector to get the single first child of element:

element.children(":first").toggleClass("redClass"); 
like image 29
Jørn Schou-Rode Avatar answered Sep 26 '22 00:09

Jørn Schou-Rode