MCN
MCN

Reputation: 123

Add span to each element of list

I have a list like this

<ul class="example">
    <li><a href="#">Something</a></li>
    <li><a href="#">Something</a></li>
</ul>

The result should be like this

<ul class="example">
    <li><a href="#"><span></span>Something</a></li>
    <li><a href="#"><span></span>Something</a></li>
</ul>

Please help me.

Upvotes: 2

Views: 1272

Answers (3)

Edison D&#39;souza
Edison D&#39;souza

Reputation: 4640

You can simply do this.

$(".example li a").each(function() {
  $(this).html(function(i, origText){
    return "<span></span>" + origText;
  });
});

Here origText contains existing inner elements. Here is the reference JQuery Tutorial

This method is very useful even when you have lot of content inside a div. Hope that helps :)

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115232

Append a span at the beginning using prepend() method.

$('ul.example li a').prepend('<span></span>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="example">
  <li><a href="#">Something</a></li>
  <li><a href="#">Something</a></li>
</ul>

Upvotes: 6

Nenad Vracar
Nenad Vracar

Reputation: 122057

You can use each() to loop each a element and change its html. DEMO

$('.example li a').each(function() {
  $(this).html('<span></span>' + $(this).text())
})

Upvotes: 0

Related Questions