How to find element by attribute in Javascript?

Member

by zita , in category: JavaScript , 2 years ago

How to find element by attribute in Javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by lucile , 2 years ago

@zita You can use either querySelector() or querySelectorAll() function in Javascript to find element(s) by attribute, below is example:


1
2
3
4
// 1 element(first)
document.querySelector('[data-attr="test"]');
// if > 1 element and return array of elements
document.querySelectorAll('[data-attr="test"]');


by jerald.kuvalis , a year ago

@zita 

To find an element by its attribute in JavaScript, you can use the querySelector method or the getElementsByTagName method with a loop to search for the desired attribute.


Here's an example using querySelector:

1
const element = document.querySelector('[data-attribute="value"]');


In this example, querySelector takes a CSS selector as its argument, and the attribute selector [data-attribute="value"] selects the element(s) with the data-attribute attribute set to "value".


Alternatively, you can use getElementsByTagName to select all elements with a particular tag name, and then filter the results by their attributes:

1
2
3
4
5
6
7
8
const elements = document.getElementsByTagName('tag-name');

for (let i = 0; i < elements.length; i++) {
  if (elements[i].getAttribute('attribute-name') === 'attribute-value') {
    const element = elements[i];
    // Do something with the element
  }
}


In this example, the loop iterates through all elements with the specified tag name and checks whether they have the desired attribute and attribute value. If so, the element is selected and can be used as needed.