Using setAttribute in JavaScript DOM (Live Playground)
In this tutorial, we will learn how to use the setAttribute
method in JavaScript to modify the values of HTML element attributes. We'll cover the basics of the setAttribute
method and provide sample code with explanations.
What is setAttribute?
The setAttribute
method is a built-in JavaScript DOM method that allows you to modify the value of a specified attribute on an HTML element. You can use the setAttribute
method to dynamically update your web page's content based on user interactions or other events.
Sample Code: Using setAttribute
Let's say we have the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>setAttribute Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph" id="firstParagraph">This is an introductory paragraph.</p>
</div>
</body>
</html>
To use setAttribute
to modify the value of an attribute on an HTML element, you'll need to include a JavaScript <script>
tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.
Here's how you can use the setAttribute
method to modify the value of the class
attribute on the p
element with the ID firstParagraph
:
<!DOCTYPE html>
<html>
<head>
<title>setAttribute Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph" id="firstParagraph">This is an introductory paragraph.</p>
</div>
<script>
// Select the element with the ID "firstParagraph"
var firstParagraph = document.getElementById('firstParagraph');
// Use setAttribute to modify the value of the "class" attribute
firstParagraph.setAttribute('class', 'updatedParagraphClass');
// Verify the updated value of the "class" attribute
console.log(
"The updated 'class' attribute value of the first paragraph is:",
firstParagraph.getAttribute('class')
);
</script>
</body>
</html>
After running this code, the p
element with the ID firstParagraph
will have its class
attribute value updated to updatedParagraphClass
. The console will display: "The updated 'class' attribute value of the first paragraph is: updatedParagraphClass".
Conclusion
The setAttribute
method is a powerful tool for modifying the values of HTML element attributes in the DOM. By mastering this method, you can dynamically update your web page's content based on user interactions or other events, creating more engaging and interactive experiences for your users.