jQuery first child of "this"

JavascriptJqueryJquery SelectorsCss Selectors

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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");

Solution 2 - Javascript

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

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

Solution 3 - Javascript

I've added [jsperf][1] test to see the speed difference for different approaches to get the first child (total 1000+ children)

given, notif = $('#foo')

jQuery ways:

  1. $(":first-child", notif) - 4,304 ops/sec - fastest
  2. notif.children(":first") - 653 ops/sec - 85% slower
  3. notif.children()[0] - 1,416 ops/sec - 67% slower

Native ways:

  1. JavaScript native' ele.firstChild - 4,934,323 ops/sec (all the above approaches are 100% slower compared to firstChild)
  2. Native DOM ele from jQery: notif[0].firstChild - 4,913,658 ops/sec

So, 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 the ele.firstChild. This gives the same identical results as regular JavaScript usage.

all tests are done in Chrome Canary build v15.0.854.0

[1]: http://jsperf.com/jquery-first-child-fetch "jQuery first child fetch"

Solution 4 - Javascript

element.children().first();

Find all children and get first of them.

Solution 5 - Javascript

Have you tried

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

I think you want to set your element as a context for your search. There might be a better way to do this which some other jQuery guru will hop in here and throw out at you :)

Solution 6 - Javascript

you can use DOM

$(this).children().first()
// is equivalent to
$(this.firstChild)

Solution 7 - Javascript

I've just written a plugin which uses .firstElementChild if possible, and falls back to iterating over each individual node if necessary:

(function ($) {
    var useElementChild = ('firstElementChild' in document.createElement('div'));

    $.fn.firstChild = function () {
        return this.map(function() {
            if (useElementChild) {
                return this.firstElementChild;
            } else {
                var node = this.firstChild;
                while (node) {
                    if (node.type === 1) {
                        break;
                    }
                    node = node.nextSibling;
                }
                return node;
            }
        });
    };
})(jQuery);

It's not as fast as a pure DOM solution, but in jsperf tests under Chrome 24 it was a couple of orders of magnitude faster than any other jQuery selector-based method.

Solution 8 - Javascript

please use it like this first thing give a class name to tag p like "myp"

then on use the following code

$(document).ready(function() {
    $(".myp").click(function() {
        $(this).children(":first").toggleClass("classname"); // this will access the span.
    })
})

Solution 9 - Javascript

This can be done with a simple magic like this:

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

Reference: http://www.snoopcode.com/jquery/jquery-first-child-selector

Solution 10 - Javascript

i am using

 $('.txt').first().css('display', 'none');

Solution 11 - Javascript

If you want immediate first child you need

    $(element).first();

If you want particular first element in the dom from your element then use below

    var spanElement = $(elementId).find(".redClass :first");
    $(spanElement).addClass("yourClassHere");

try out : http://jsfiddle.net/vgGbc/2/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmacca1View Question on Stackoverflow
Solution 1 - JavascriptShog9View Answer on Stackoverflow
Solution 2 - JavascriptJørn Schou-RodeView Answer on Stackoverflow
Solution 3 - JavascriptmanikantaView Answer on Stackoverflow
Solution 4 - JavascriptBishal PaudelView Answer on Stackoverflow
Solution 5 - JavascripttheIVView Answer on Stackoverflow
Solution 6 - JavascriptYukuléléView Answer on Stackoverflow
Solution 7 - JavascriptAlnitakView Answer on Stackoverflow
Solution 8 - Javascriptvishal guptaView Answer on Stackoverflow
Solution 9 - JavascriptPrabhakar UndurthiView Answer on Stackoverflow
Solution 10 - Javascriptfahimeh ahmadiView Answer on Stackoverflow
Solution 11 - JavascriptAmit RathodView Answer on Stackoverflow