Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 245
Shaoz Avatar asked Dec 09 '10 13:12

Shaoz


People also ask

What is getElementsByTagName in JavaScript?

The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection.

What is equivalent of get elements by tag name in jQuery?

Using jQuery selector, you can select an element by tag name. The jQuery element selector selects elements.

What is $element in jQuery?

Description: Selects all elements with the given tag name.

What does getElementsByTagName return?

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.


2 Answers

$("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/
like image 77
karim79 Avatar answered Oct 13 '22 08:10

karim79


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.

like image 41
James Wiseman Avatar answered Oct 13 '22 06:10

James Wiseman