To get an element by attribute in JavaScript, you can use the getElementsByTagName()
method to get all elements with a particular tag name and then loop through them to find the one with the desired attribute using the getAttribute()
method. Here's an example:
index.tsx489 chars17 lines
In this example, we're getting all div
elements on the page using getElementsByTagName()
. Then we're looping through each div
and using getAttribute()
to get the value of the class
attribute. We check if the class
attribute matches our desired value ("my-class" in this case). Once we've found the element we're looking for, we output it to the console and exit the loop using the break
statement.
gistlibby LogSnag