Coder Perfect

“this” is the first child of jQuery.

Problem

I’m trying to send “this” from a clicked span to a jQuery method that can then run jQuery on the first child of that clicked element. I’m having trouble getting it correctly…

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

Javascript:

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

How do I refer to the element’s first-born child?

Asked by macca1

Solution #1

Use the find() function to apply a selector to the context provided by an existing jQuery set:

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

Jrn Schou-Rode pointed out that you’re probably only looking for the context element’s first direct descendant, which is why the child selector (>) is used. He also mentions that the children() function, which is comparable to find() but only searches one level deep in the hierarchy (which is all you need…), could be used instead:

element.children(":first").toggleClass("redClass");

Answered by Shog9

Solution #2

To get the single first child of element:first, use the children function with the:first selection.

element.children(":first").toggleClass("redClass");

Answered by Jørn Schou-Rode

Solution #3

I’ve added a jsperf test to check how alternative techniques to getting the first kid (total 1000+ children) compare in terms of speed.

$(‘#foo’) supplied, notif =

jQuery ways:

Native ways:

As a result, the first three jQuery techniques are not advised, at least for first-time users (I doubt that would be the case with many other too). If you have a jQuery object and need to get the first-child, use array reference [0] (preferred) or.get(0) to acquire the native DOM element from the jQuery object and use ele.firstChild. This produces the same results as using ordinary JavaScript.

Chrome Canary build v15.0.854.0 was used for all experiments.

Answered by manikanta

Solution #4

element.children().first();

Find all of the children and take the first one.

Answered by Bishal Paudel

Solution #5

Have you tried

$(":first-child", element).toggleClass("redClass");

I believe you should use your element as a search context. There might be a better method to handle this, which some other jQuery expert will chime in with:)

Answered by theIV

Post is based on https://stackoverflow.com/questions/2275702/jquery-first-child-of-this