jQuery first child of “this”

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…

Javascript:
function toggleSection(element) {
element.toggleClass(“redClass”);
}

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

Solutions/Answers:

Solution 1:

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:

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

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

Solution 3:

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:

  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.firstChild4,934,323 ops/sec (all the above approaches are 100% slower compared to firstChild)
  2. Native DOM ele from jQery: notif[0].firstChild4,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

Solution 4:

element.children().first();

Find all children and get first of them.

Solution 5:

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:

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.