jQuery first child of “this”

后端 未结 10 1129
暖寄归人
暖寄归人 2020-12-04 05:48

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

相关标签:
10条回答
  • 2020-12-04 06:10

    you can use DOM

    $(this).children().first()
    // is equivalent to
    $(this.firstChild)
    
    0 讨论(0)
  • 2020-12-04 06:10

    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.

    0 讨论(0)
  • 2020-12-04 06:13

    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

    0 讨论(0)
  • 2020-12-04 06:14

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

    0 讨论(0)
提交回复
热议问题