JavaScript – Get Attributes of Paragraph Element
To get attributes of a paragraph using JavaScript, get reference to the paragraph element, and read the attributes
property of the paragraph element.
In the following example, we have paragraph element with id "myPara"
, and we shall get the attributes of this paragraph element in JavaScript using attributes
property.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Attributes of Paragraph using JavaScript</h2>
<p id="myPara" class="dummy">This is a paragraph.</p>
<button type="button" onclick="getAttributes()">Click Me</button>
<script>
function getAttributes(){
var element = document.getElementById("myPara");
var attribs = element.attributes;
console.log(attribs);
}
</script>
</body>
</html>
Try this program online, and open Developer Tools. Open Console window.
Click on the ‘Click Me’ button in our HTML page. The following shall be displayed in the console window.
attributes
property returns NameNodeMap object with the attributes in it, where the attributes can be accessed using name of the attribute or the index.
Conclusion
In this JavaScript Tutorial, we learned how to get the attributes of a paragraph element using JavaScript.