Home > Software design >  is there a way to find HTML element by type?
is there a way to find HTML element by type?

Time:01-26

There are several functions to get DOM document elements e.g. .getElementById(), .getElementByName() etc. but I do not see any function which would allow to get element by type.

Is there some mechanism to do it?

CodePudding user response:

You can use the getElementsByTagName() function to get all elements by their tag name.

I.e. getElementsByTagName("div") will return all <div>'s.

CodePudding user response:

CSS selectors via .querySelectorAll are most powerful.

let p = document.querySelectorAll("p");
console.log(p[0].innerHTML   " and "   p[1].innerHTML);
<p>asdf</p>
<span>fdafsdf</span>
<p>kjkjkj</p>

CodePudding user response:

You can get all elements by the type with 'document.querySelectorAll()' method. As an example, you can get all the 'input' elements with type 'text' as follows.

document.querySelectorAll('input[type="text"]')

  • Related