2

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?

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

Comments

1

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

a.appendChild(text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.