Skip to content
Advertisement

Javascript: can’t add href to list item

I am trying to add a new item to a list item. But the below code isn’t adding Hyperlink to the list item I want. Can someone please advise what’s wrong?

HTML:

<div>
    <ul id="list1">
      <li>Ut enim ad minim veniam.</li>
      <li>Excepteur sint occaecat cupidatat non proident.</li>
    </ul>
</div>

JavaScript:

//create new li element
var newListItem = document.createElement("li");
newListItem.textContent = "...ooo";
var ulist = document.getElementById("list1");
console.log("adding link..");
newListItem.setAttribute('href', "http://www.msn.com");
ulist.appendChild(newListItem);
console.log("added item");

Advertisement

Answer

li doesn’t have the href attribute, you have to wrap an a tag inside li.

var a = document.createElement("a");
var ulist = document.getElementById("list1");
var newItem = document.createElement("li");

a.textContent = "...ooo";
a.setAttribute('href', "http://www.msn.com");
newItem.appendChild(a);
ulist.appendChild(newItem);

The DEMO.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement