What's the equivalent of 'getElementsByTagName' in jQuery?

后端 未结 4 1094
说谎
说谎 2020-12-29 03:24

What\'s the equivalent of getElementsByTagName() in jQuery? I just want to create a collection of elements in jQuery so I can iterate through them and do someth

相关标签:
4条回答
  • 2020-12-29 03:49

    Given a string tagName, this statement:

    document.getElementsByTagName(tagName)
    

    ...could be written using jQuery:

    $(tagName)
    

    Given a native DOM element element and a string tagName, this statement:

    element.getElementsByTagName(tagName)
    

    ...could be written using jQuery:

    $(element).find(tagName)
    

    Note : Using getElementsByTagName you get native DOM elements, meanwhile using jQuery statements you get jQuery objects. If you want native DOM elements with jQuery you could use get() - How do I pull a native DOM element from a jQuery object?

    0 讨论(0)
  • 2020-12-29 03:54
    $("tagnamehere")
    

    So:

    $("div").each(function() {
        // do something exciting with each div
        $(this).css("border", "1px solid red");
    
        // do something by directly manipulating the wrapped DOM element
        this.style.border = "1px solid red";
    
        // do something only if this particular div has a class of 'pretty'
        if($(this).hasClass("pretty")) {
            $(this).text("I am the pretty one");
        }
    });
    

    or just:

    // apply some css to all div elements
    $("div").css("border", "1px solid red");
    

    Keep in mind that when you use jQuery to select a number of elements, e.g. $("span"), any method you invoke on the object will happen on all matched elements. Think of it as 'implicit iteration' - e.g. $("span").hide(); will hide all span elements on the page.

    See:

    • http://www.w3.org/TR/css3-selectors/
    • http://api.jquery.com/category/selectors/
    • http://api.jquery.com/each/
    0 讨论(0)
  • 2020-12-29 04:00

    Just need put something like:

    var some = $('[name="tagname"]');
    
    0 讨论(0)
  • 2020-12-29 04:05

    Just use the element selector

    $('elementname')
    

    E.g.

    $('div')
    

    And to do the iteration:

    $('div').each(function(){
        var $this = $(this);
        //insert code here
    });
    

    You may not have to iterate, however, as a method called upon the collection will be called for each item in the collection, so

    $('div').hide();
    

    ...will hide all divs.

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