Ruth Ruth - 2 months ago 8
Javascript Question

Insert a link tag into each list element

I want to insert a link between the two list items in each ul element. At the moment my code only inserts the link in the last ul element.

<html>
<div class="list">
<ul>
<li>what</li>
<li>now</li>
</ul>
</div>
<div class="list">
<ul>
<li>what</li>
<li>now</li>
</ul>
</div>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var tag = document.createElement("A")
var linkedTag = tag.setAttribute('href', '/');
tag.innerHTML = "UP"

$('.list').each(function(i, obj) {
var one = obj.childNodes[1];
one.insertBefore(tag, one.childNodes[2])
});
</script>
</html>

Answer

There's a much easier way to do that with jQuery

$('.list').append(function() {
    return $('<a>', { href : '/', text : 'UP' })
});

The reason your code doesn't work, is because you only create one single anchor, and move it, so it ends up in the last place it was moved to.

Also note that inserting an anchor directly in an UL, which is what you're doing, is invalid markup. If you wanted to place an anchor before each UL, you'd do

$('.list ul').prepend(function() {
    return $('<a>', { href : '/', text : 'UP' })
});

If you want the anchor inbetween the two already existing LI elements, you'd have to wrap that anchor in a LI element as well

$('.list ul li:first-child').after(function() {
    return $('<li>', {
        html : $('<a>', { href : '/', text : 'UP' })
    });
});

FIDDLE