The code I have:
var add = $(items).find('li').each(function() {
return $(this).append('
');
});
This gives me the following DOM output:
<li><a href="#"><img src="image1"></a></li>
<li><a href="#"><img src="image2"></a></li>
<li><a href="#"><img src="image3"></a>
</li><li><a href="#"><img src="image4"></a>
</li><li><a href="#"><img src="image5"></a>
What I want is for the new line to be appended after the </li>
tag. Like this:
<li><a href="#"><img src="image1"></a></li>
<li><a href="#"><img src="image2"></a></li>
<li><a href="#"><img src="image3"></a></li>
<li><a href="#"><img src="image4"></a></li>
<li><a href="#"><img src="image5"></a></li>
I have realized that appending is not the right choice here but trying with .after()
and .before()
didn't produce any results either. In fact, both methods produce the same output:
<li><a href="#"><img src="image1"></a></li>
<li><a href="#"><img src="image2"></a></li>
<li><a href="#"><img src="image3"></a></li>
<li><a href="#"><img src="image4"></a></li><li><a href="#"><img src="image5"></a></li>
So how can I achieve this?
EDIT:
This is the example php
code that is generating images. Of course there are other conditions that tells when to close ul
and start a new one but this is what generates the new lines in source code and whitespaces between images:
echo '<li><a href="'.$image.'" ><img src="'.$thumb.'"/></a></li>'."
";
As said if I remove from
php
, then it's fine but the source code is then one-liner.
.append()
adds a new element inside the given element(s). You want .after()
.
$(items).find("li").after("
");
There's no need to use .each()
, the DOM modification methods automatically operate on all the elements in the collection. And when using .each()
you don't need to return anything, it always returns the original collection.
Note that there's little point in adding a newline between <li>
elements, I don't think it will have any effect on the rendering of the list. Whitespace like this is useful in HTML source code, but it's irrelevant to the DOM.