Shaoz
Shaoz

Reputation: 10653

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

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 something with each item.

Many thanks!

Upvotes: 37

Views: 96793

Answers (4)

boumbh
boumbh

Reputation: 2080

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?

Upvotes: 4

Geovas
Geovas

Reputation: 67

Just need put something like:

var some = $('[name="tagname"]');

Upvotes: -4

karim79
karim79

Reputation: 342775

$("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:

Upvotes: 49

Mutation Person
Mutation Person

Reputation: 30520

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.

Upvotes: 7

Related Questions