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
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?
$("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:
Just need put something like:
var some = $('[name="tagname"]');
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.