Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all elements of a particular HTML tag in javascript?

Tags:

javascript

I need to hide all elements of type 'section' in my document apart from one with a particular ID.

In jquery this would be easy

$("section").hide();
$("section#myId").show();

How would I do this without jquery??

(I need it to happen as soon as the page loads and to not be noticable). I also need it to work cross browser.

Thanks.

like image 635
Tom Avatar asked Jul 27 '11 10:07

Tom


People also ask

How can we fetch all attributes for an HTML element in JavaScript?

To get all of the attributes of a DOM element: Use the getAttributeNames() method to get an array of the element's attribute names. Use the reduce() method to iterate over the array. On each iteration, add a new key/value pair containing the name and value of the attribute.

How do I get the content of a tag in HTML?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.

How will you select all the elements by a tag name?

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


2 Answers

DOMElement.getElementsByTagName is your friend:

var sections = document.getElementsByTagName('section');
var mySection = null;
for(var i = 0; i < sections.length; ++i) {
   if(sections[i].id === "myId") {
      mySection = sections[i];
      mySection.style.display = "block";
      break;
   }
   sections[i].style.display = "none";
}
like image 141
Jacob Relkin Avatar answered Oct 16 '22 03:10

Jacob Relkin


Place the following immediately before the </body> in your HTML

<script>
(function () {
  for(var els = document.getElementsByTagName ('section'), i = els.length; i--;)
    els[i].id !== "myId" && (els[i].style.display = "none");
}) ();
</script>

or in "modern" (HTML5) browsers :

<script>
  [].forEach.call (document.querySelectorAll ('section'),
    function (el) { el.id !== "myId" && (el.style.display = "none"); })
</script>
like image 44
HBP Avatar answered Oct 16 '22 02:10

HBP