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!
The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection.
Using jQuery selector, you can select an element by tag name. The jQuery element selector selects elements.
Description: Selects all elements with the given tag name.
getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. Therefore, there is no need to call Element.
$("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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With