| by Arround The Web | No comments

How to Get Element by Attribute in JavaScript

While developing websites, there are some situations where programmers/developers need to get the elements in JavaScript using their assigned attributes such as “id”, “class”, and so on. To do this, use the JavaScript “querySelector()” method.

This tutorial will explain the process for getting the HTML element by attribute using JavaScript.

How to Get Element by Attribute in JavaScript?

To get an element by attribute, the “querySelector()” method is used. It returns the document’s first element that matches the particular attribute. This method selects a particular tag with a specific attribute value. The parameters that need to be passed are the “TagID”, “class”, and so on.

Syntax
Use the below-mentioned syntax for getting the element by attribute:

document.querySelector("[myAttribute=value]");

In the above syntax, pass the attribute with its assigned value as a parameter.

Example
In the HTML file, first, create a “div” element using the <div> tag and assign an id “divId” to it. Create a button inside the div element and attach an “onclick” event that will trigger the “getElement()” method for getting the element:

<div id="divId">Click to Get Element<br><br>
 <button onclick="getElement()">Click</button>
</div>

For styling the div, we will use the below lines of code:

#divId {
 padding: 10px;
 height: 100px;
 width: 200px;
 margin: auto;
 background-color: pink;
}

The corresponding output will be as follows:

In the JavaScript file, define a function “getElement()” that will trigger while the button is clicked. Call the “querySelector()” method and pass the attribute “id” and its value “divId” as an argument and store the resultant element in a variable “element”:

function getElement(){
 var element = document.querySelector('[id="divId"]');
 alert(element);
}

The given output shows that the attribute “divId” belongs to an element “div”:

If you want to see all the elements inside the specific element, instead of calling the alert() method use the “console.log()” method that will show the element including its child elements.

function getElement(){
 var element = document.querySelector('[id="divId"]');
 console.log(element);
}

Output

The above GIF shows the HTML “div” element that has an attribute with the value “divId”, with its child elements in the console by clicking on the button.

Conclusion

For getting an element by attribute, use the JavaScript predefined “querySelector()” method. It is used to select a particular tag with a specific attribute value. This tutorial explains the process for getting the HTML element by attribute using JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply