Javascript DOM Attribute Create

Description

Javascript DOM Attribute Create

View in separate window


<!DOCTYPE html>
<head>
<title>Recipe</title>
<meta charset="utf-8" />
<script>

window.onload=function() {/*from   w w  w .j a v  a2 s.  c om*/

// first approach

let targetNode = document.getElementById("target");
let newAttr = document.createAttribute("newattr");
newAttr.nodeValue = "red";
targetNode.setAttributeNode(newAttr);
console.log(targetNode.getAttribute("newattr"));

// second approach
targetNode.setAttribute("newattr2","blue");
console.log(targetNode.getAttribute("newattr2"));

}
</script>

</head>
<body>
<div id="target">This is a paragraph in a div element</div>
</body>
</html>



PreviousNext

Related