Javascript: cannot add href to item list

I am trying to add a new item to a list item. But the code below does not add a hyperlink to the list item that I want. Can someone please report what happened?

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");
+3
source share
4 answers

lihas no attribute href, you have to wrap the tag ainside 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);

Demo.

+7
source

An attribute hrefdoes not make sense for an element <li>. If you want to create a list item in a link, you will need to wrap its contents in the item <a>and apply to it href.

+1
source

jsBin

var ulist = document.getElementById("list1");
var newListItem = document.createElement("li");
var newAnchor = document.createElement("a");
newAnchor.textContent = "...ooo";
newAnchor.setAttribute('href', "http://www.msn.com");
newListItem.appendChild(newAnchor);
ulist.appendChild(newListItem);

yep, anchor.

0

, :)

:

`` [...] . HTML , , . [...] ''

, <ul> . , , :

, a ul. href ul?

.

, ( , ), . ( , .)

ul :

:

  • Accesskey
  • contenteditable
  • Dropzone
  • ID
  • TabIndex

, , onmouseover, onclick, on... ARIA. , , href.

, :

  • ul .
  • ul href.

href li!

li ul/ol , ul. li : li:

. a .

? li :


  • ol: value -

, :

  • ul .
  • ul href.
  • li .
  • li href.

As indicated by others, we should add it to the anchor, which we put as a child li:

<ul>
    <li><a href="myurl">Hello</a></li>
</ul>
0
source

All Articles