JQuery - How to add a single html tag to some html?

Keith Donegan picture Keith Donegan · May 11, 2010 · Viewed 10.4k times · Source

I want to insert just a single <span> before the text below (right before LINK):

<li><a href="">LINK</a></li>

So, the above becomes

<li><a href=""><span>LINK</a></li>

Here is my JQuery Code:

$('#mainnav li a').prepend('<span>');

When I view the code in firebug after, I see <span></span>, how do I just get the opening span tag and not the closing tag?

Answer

cletus picture cletus · May 11, 2010

Firstly, what you want is malformed HTML. jQuery is going to make it hard if not impossible to create that. I would suggest doing it in a single step rather than multiple. Try:

$("li > a").each(function() {
  $(this).contents().wrapAll("<span>");
});

Input:

<ul>
  <li><a href="...">testing</a></li>
  <li><a href="...">rich <b>content</b> with <i>inner tags</i></a></li>
</ul>

Output:

<ul>
  <li><a href="..."><span>testing</span></a></li>
  <li><a href="..."><span>rich <b>content</b> with <i>inner tags</i></span></a></li> 
</ul>