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?
If you want immediate first child you need
If you want particular first element in the dom from your element then use below
try out : http://jsfiddle.net/vgGbc/2/
If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:
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...):
This can be done with a simple magic like this:
Reference: http://www.snoopcode.com/jquery/jquery-first-child-selector
Find all children and get first of them.
you can use DOM
I've added jsperf test to see the speed difference for different approaches to get the first child (total 1000+ children)
given,
notif = $('#foo')
jQuery ways:
$(":first-child", notif)
- 4,304 ops/sec - fastestnotif.children(":first")
- 653 ops/sec - 85% slowernotif.children()[0]
- 1,416 ops/sec - 67% slowerNative ways:
ele.firstChild
- 4,934,323 ops/sec (all the above approaches are 100% slower compared tofirstChild
)notif[0].firstChild
- 4,913,658 ops/secSo, first 3 jQuery approaches are not recommended, at least for first-child (I doubt that would be the case with many other too). If you have a jQuery object and need to get the first-child, then get the native DOM element from the jQuery object, using array reference
[0]
(recommended) or.get(0)
and use theele.firstChild
. This gives the same identical results as regular JavaScript usage.all tests are done in Chrome Canary build v15.0.854.0