[javascript] 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?

This question is related to javascript jquery jquery-selectors css-selectors

The answer is


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 :)


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.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


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/


element.children().first();

Find all children and get first of them.


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.
    })
})

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.


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


you can use DOM

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

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to css-selectors

Angular 2: How to style host element of the component? How to click a href link using Selenium How do I apply a style to all children of an element How to write a CSS hack for IE 11? :last-child not working as expected? Need to find element in selenium by css jQuery select child element by class with unknown path How do I select an element that has a certain class? What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing? What is the mouse down selector in CSS?