Anthuan Vásquez
Anthuan Vásquez

Reputation: 4716

Add Tag After and Before elements with jQuery

Assuming I have this markup:

<li class="cat-item"><a href="#">Item 1</a> 5 </li>
<li class="cat-item"><a href="#">Item 2</a> 9 </li>
<li class="cat-item"><a href="#">Item 3</a> 4 </li>
<li class="cat-item"><a href="#">Item 4</a> 3 </li>
<li class="cat-item"><a href="#">Item 5</a> 7 </li>

I want insert a span tag after <li><a>item</a> and before </li> thus being.

<li class="cat-item"><a href="#">Item 1</a><span> 5 </span></li>
<li class="cat-item"><a href="#">Item 2</a><span> 9 </span></li>
<li class="cat-item"><a href="#">Item 3</a><span> 4 </span></li>
<li class="cat-item"><a href="#">Item 4</a><span> 3 </span></li>
<li class="cat-item"><a href="#">Item 5</a><span> 7 </span></li>

I want to do with jQuery. Anyone know how?

Upvotes: 4

Views: 3318

Answers (2)

TheHe
TheHe

Reputation: 2972

This will insert an empty span tag after each a tag in li.cat-item:

$('li.cat-item a').after('<span />');

See jQuery - after()

Upvotes: 1

Musa
Musa

Reputation: 97672

Try

$('li.cat-item a').each(function(){
    $(this.nextSibling).wrap('<span>');
});

This wraps the text node after the <a> (i.e. its nextSibling) in a <span>

DEMO

Upvotes: 7

Related Questions