Reputation: 29
So, Im currently taking classes to start a career in the coding industry, and Im stuck on this exercise:
Inside the div below, insert a span tag that has a class name of content and says "You got this!".
<div id="wrapper"></div>
Ive been at this for a couple days now, and this is the best attempt I think I've had so far.
var span = document.createElement('span');
span.className = 'content';
var text = document.createTextNode("You got this!");
wrapper.appendChild(text);
document.getElementById('wrapper').appendChild(span);
Any help would be appreciated, thank you.
Upvotes: 2
Views: 895
Reputation: 8098
All the above answers cover much of it. I will cover adding class="content"
to the span
, which is also the part of this question.
We can use setAttribute()
property to add any property on our HTML element.
So doing span.setAttribute("class","content")
will set also set the class="content"
for the span element. Below code will also work fine:
let span = document.createElement("span");
let textnode = document.createTextNode("You got this!");
span.setAttribute("class","content");
span.appendChild(textnode);
document.getElementById("wrapper").appendChild(span);
<div id="wrapper"></div>
Upvotes: 1
Reputation: 688
You needed to append the text to the span variable, not to "wrapper":
span.appendChild(text);
var span = document.createElement('span');
span.className = 'content';
var text = document.createTextNode("You got this!");
span.appendChild(text);
document.getElementById('wrapper').appendChild(span);
<div id="wrapper"></div>
Simpler answer :
On a side note, you could also directly insert the text in the document without having to use a second variable like so :
var span = document.createElement('span');
span.className = 'content';
document.getElementById('wrapper').appendChild(span);
span.innerHTML = 'You got this!';
<div id="wrapper"></div>
Here is the JSFiddle.
Upvotes: 3
Reputation: 1749
If you want to add text only one span that's class is content, I think you can do like this.
var span = document.createElement('span');
span.classList.add("content");
var text = document.createTextNode("You got this!");
var content = document.getElementsByClassName("content");
content.item(0).appendChild(text);
document.getElementById('wrapper').appendChild(span);
Or if you don't need only that, you can do like this.
var span = document.createElement('span');
span.classList.add("content");
var text = document.createTextNode("You got this!");
span.appendChild(text);
document.getElementById('wrapper').appendChild(span);
Upvotes: 0
Reputation: 1259
I believe you intended to write span.appendChild(text);
instead of wrapper.appendChild(text);
, because you want the TextNode to be appended to the span, not the wrapper.
If you encounter any problem or question while implementing my solution, please let me know in a comment.
Upvotes: 2