简体   繁体   中英

Unordered List, List Item, JS / HTML Question

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?

The Issue

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>

The Solution

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> 

Try this:

 var a = document.createElement('a'); a.setAttribute('href', 'foo.com'); a.appendChild(document.createTextNode('bar')); console.log(a); 

The text is a child of the a tag, not the li tag.

a.appendChild(text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM