Reputation: 55
I found a few posts referencing something similar but I could not get it working..
Simply I am trying to create a List as shown below.
<ul>
<li><a href="https://www.google.com">foo</a> </li>
<li><a href="https://www.google.com">bar</a></li>
</ul>
However when generating it through JS I get one of the following.
<ul>
<li>
<a href="https://www.google.com"></a>
foo
</li>
<li>
<a href="https://www.google.com"></a>
bar
</li>
</ul>
OR
<ul>
<li>
foo
<a href="https://www.google.com"></a>
</li>
<li>
bar
<a href="https://www.google.com"></a>
</li>
</ul>
With the JS code provided.
function addListItem(id, str, url) {
var list = document.getElementById(id);
var el = document.createElement("LI");
var text = document.createTextNode(str);
if (url !== "") {
var a = document.createElement("A");
a.setAttribute("href", url);
el.appendChild(text);
el.appendChild(a);
} else {
el.appendChild(text);
}
list.appendChild(el);
}
How would I go about doing this?
Upvotes: 2
Views: 51
Reputation: 21672
Take a look at these two lines:
el.appendChild(text);
el.appendChild(a);
First, you append the text...
<li>
foo
</li>
Then you append the <a>
...
<li>
foo
<a href="https://www.google.com"></a>
</li>
What you need to do instead, is append your text to your <a>
first:
a.appendChild(text);
<a href="https://google.com">foo</a>
Then append that to your <li>
:
el.appendChild(a);
<li><a href="https://google.com">foo</a></li>
Corrected version:
function addListItem(id, str, url) {
var list = document.getElementById(id);
var el = document.createElement("LI");
var text = document.createTextNode(str);
if (url !== "") {
var a = document.createElement("A");
a.setAttribute("href", url);
a.appendChild(text);
el.appendChild(a);
} else {
el.appendChild(text);
}
list.appendChild(el);
}
addListItem("list", "foo", "https//google.com");
<ul id="list"></ul>
Upvotes: 2
Reputation: 1025
The text is a child of the a tag, not the li tag.
a.appendChild(text);
Upvotes: 1
Reputation: 27224
Try this:
var a = document.createElement('a');
a.setAttribute('href', 'foo.com');
a.appendChild(document.createTextNode('bar'));
console.log(a);
Upvotes: 1