Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Tag After and Before elements with jQuery

Tags:

html

jquery

tags

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?

like image 792
Anthuan Vásquez Avatar asked Feb 20 '23 08:02

Anthuan Vásquez


2 Answers

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

like image 99
Musa Avatar answered Feb 21 '23 20:02

Musa


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

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

See jQuery - after()

like image 40
TheHe Avatar answered Feb 21 '23 20:02

TheHe