How to extend jQuery to make it easier to retrieve the tagName

前端 未结 4 512
不思量自难忘°
不思量自难忘° 2020-12-06 09:32

I am looking to extend jQuery so I can easily retrieve the tagName of the first element in a jQuery object. This is what I have come up with, but it doesn\'t seem to work:

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 10:20

    This one will return the lower case tagname of the matched element.

    for example,

    jQuery("#test_div").tagName();
    

    would return div (assuming that element was a div).

    If you pass an element collection, it returns an array of all the tagnames, where each array entry corresponds to the matched element.

    for example if we run

    jQuery(".classname").tagName();
    

    on the following (X)HTML:

    test text

    Some more text

    would an array of tagnames:

    ["p", "li", "p"]
    

    This is the function - it's basically the same as above but it supports multiple elements, which may or may not be useful to your project.

    jQuery.fn.tagName = function(){
        if(1 === this.length){
            return this[0].tagName.toLowerCase();
        } else{
            var tagNames = [];
            this.each(function(i, el){
                tagNames[i] = el.tagName.toLowerCase();
            });
            return tagNames;
        }
    };
    

提交回复
热议问题