0

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.

2
  • 2
    The return value of appendChild is the appended child node. In code 2, x is a text node, not a span. Commented Sep 22, 2020 at 12:36
  • x is a text node and you can't call setAttibute(...) on a text node. Commented Sep 22, 2020 at 12:38

1 Answer 1

2

appendChild returns the appended child, not the parent. Hence

var x = document.createElement("SPAN").appendChild(y);

is the same as

var x = y;

Since x (and y) refer to a TextNode, setting an attribute on them won't have any effect (only elements can have attributes).


Just want to write whole script in one line.

That's unnecessary, however, you can put as many statements in a line as you want, as long as they are separated be ;.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.