JavaScript DOM Element Methods Tutorial
setAttribute()
- Sets the value of an attribute of the given element.
<div id="myDiv"></div>
document.getElementById("myDiv").setAttribute("style", "color: red;");
This will set the style attribute of the div element with the ID myDiv to the value "color: red;".
getAttribute()
- Gets the value of an attribute of the given element.
<div id="myDiv" style="color: red;"></div>
const style = document.getElementById("myDiv").getAttribute("style");
console.log(style); // "color: red;"
This will get the value of the style attribute of the div element with the ID myDiv and assign it to the variable style.
removeAttribute()
- Removes an attribute from the given element.
<div id="myDiv" style="color: red;"></div>
document.getElementById("myDiv").removeAttribute("style");
This will remove the style attribute from the div element with the ID myDiv.
getAttributeNode()
- Gets the attribute node (if any) corresponding to the given attribute name.
<div id="myDiv" style="color: red;"></div>
const styleNode = document.getElementById("myDiv").getAttributeNode("style");
console.log(styleNode); // Attr object representing the `style` attribute
This will get the attribute node (an Attr object) corresponding to the style attribute of the div element with the ID myDiv.
setAttributeNode()
- Sets the attribute node (if any) corresponding to the given attribute name.
<div id="myDiv"></div>
const styleNode = document.createAttribute("style");
styleNode.value = "color: red;";
document.getElementById("myDiv").setAttributeNode(styleNode);
This will create an attribute node (an Attr object) with the name style and the value "color: red;" and set it as the style attribute of the div element with the ID myDiv.
removeAttributeNode()
- Removes the attribute node (if any) corresponding to the given attribute name.
<div id="myDiv" style="color: red;"></div>
const styleNode = document.getElementById("myDiv").getAttributeNode("style");
document.getElementById("myDiv").removeAttributeNode(styleNode);
This will remove the attribute node (an Attr object) corresponding to the style attribute of the div element with the ID myDiv.
getElementsByTagName()
- Returns a list of all elements in the document with the given tag name.
<div id="myDiv"></div>
<div id="myDiv2"></div>
const divs = document.getElementsByTagName("div");
console.log(divs.length); // 2