how to get an element by attribute in javascript

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.tsx
// Get all elements with tag name "div"
var divs = document.getElementsByTagName("div");

// Loop through all divs
for (var i = 0; i < divs.length; i++) {

  // Get the class attribute of the current div
  var classAttr = divs[i].getAttribute("class");

  // Check if the class attribute matches the desired value
  if (classAttr === "my-class") {
    // Found the element with the desired attribute!
    console.log(divs[i]);
    break; // Stop looping once we've found the element
  }
}
489 chars
17 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