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");
The
href
attribute is not meaningful on an<li>
element. If you want to make an list element into a link, you will need to wrap its contents in an<a>
element and apply thehref
to that.li
doesn't have thehref
attribute, you have to wrap ana
tag insideli
.The DEMO.
jsBin
yep so basically you missed the
anchor
tag creation.Though solved, I add some more information for you to read :)
Content and attributes
Each element has a content model:
As such the
<ul>
element has a content model. Looking at the specs we find it to be:By this we can conclude that we can not have an anchor,
a
, inside theul
element. But what about adding ahref
attribute to theul
?Then we look at the Content attributes.
For
ul
we find:The Global attributes are the following:
In addition it can have various event handler attributes, like
onmouseover
,onclick
,on...
and ARIA attributes. But, as we see, nohref
attribute.In conclusion we now know that:
ul
can not have an anchor as a child.ul
can not have thehref
attribute.But, the question was about
href
onli
element!As
li
andul
/ol
are intertwined we first had a look atul
. Forli
we follow the same procedure: The content model forli
is:Now, that opens up a wide range of possibilities. Here we find
a
at top of the list.And what about the attributes? For
li
we find:If the element is a child of an ol element: value - Ordinal value of the list item
In other words, we now know:
ul
can not have an anchor as a child.ul
can not have thehref
attribute.li
can have an anchor as a child.li
can not have thehref
attribute.Solution
As pointed out by others, is to add it to an anchor that we put as a child of a
li
element: