getElementsByTagName() in javascript

getElementsByTagName() method in javascript

getElementsByTagName() method is used to select every element with the specified tag name.

When using this method, it converts the given input value into lowercase, so it is not suitable when searching camel-cased element.

So instead of this, getElementsByTagNameNS() method can be used.

Example - Getting the element with specified tag name

Try Yourself

Example Explanation

  • In the above example we have two h1 and p elements, button and a Javascript function is declared for it (fun_name();).
  • When the button is clicked Javascript function is called.
  • In the Javascript function, first we are getting the h1 elements with its specified tag name(getElementsByTagName("h1");) and storing in elem variable.
  • In the next step a for loop is created and every element in elem variable is displayed (alert(elem2.outerHTML);).