Code1:
<html>
<body>
<div id="test"></div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var y = document.createTextNode("This is a span element.");
var x = document.createElement("SPAN");
x.appendChild(y);
document.getElementById("test").appendChild(x).setAttribute("style", "background-color: red;");
}
</script>
</body>
</html>
Code 2:
<script>
function myFunction() {
var y = document.createTextNode("This is a span element.");
var x = document.createElement("SPAN").appendChild(y);
document.getElementById("test").appendChild(x).setAttribute("style", "background-color: red;");
}
</script>
Why attribute is not setting for span? In code 1 I am getting required output ie red background for text but in code 2 it seems I am not getting that.
Just want to write whole script in one line.
appendChildis the appended child node. In code 2,xis a text node, not aspan.xis a text node and you can't callsetAttibute(...)on a text node.