find out if an element exists by name in javascript

To check if an element exists by name in javascript, you can use the document.getElementsByName method. This method returns a NodeList of all the elements with the specified name attribute.

You can then check if the NodeList is empty or not to determine if an element exists. Here's an example:

index.tsx
let elements = document.getElementsByName("example");
if (elements.length) {
  // element with name "example" exists
  // do something with the element(s)
} else {
  // element with name "example" does not exist
  // handle the error
}
236 chars
9 lines

In this example, we're using document.getElementsByName to get all elements with the name "example". We then check the length of the NodeList to see if it's greater than 0. If it is, the element exists and we can do something with it. If it's not, the element does not exist and we can handle the error accordingly.

Note that getElementsByName returns a live NodeList, meaning that changes to the DOM will be reflected in the list. If you know there is only one element with the given name you could use document.getElementsByName("example")[0] to get the first one.

related categories

gistlibby LogSnag