views:

242

answers:

4

Hey Guys,

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 , how do I just get the opening span tag and not the closing tag?

A: 

When you use prepend, you're not adding markup text to the page, you're adding elements to the page. Elements don't have "start" and "end" tags, elements are elements. If you want to wrap a bunch of elements in a span (I'm guessing that's what you want, if you want to insert the beginning of it in one place and the end of it in another), you need to add the span to the container and then move the elements into it.

For example, this moves all of the links out of the element foo and moves them into a span inside container:

var stuff;
var container;

stuff = $('#foo a');
span = $("<span style='background-color: yellow'>");
span.append(stuff);
$('#container').append(span);
T.J. Crowder
+3  A: 

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>
cletus
A: 

I don't know why you want it but it can be done this way,

$('#mainnav li a').html(function(i,v){
   return '<span>' + v;
})
Reigel
A: 

Many jQuery methods are designed to automatically create elements from only half-written tags, like, "<span>" for a .prepend() will result in an entire span element being added to the DOM. Or, as you'll see it in Firebug, "<span></span>" inserted firstly in the anchor element.

I don't see why you'd want to create invalid HTML, but if you must, you can do it this way:

$("li > a").html("<span>"+$("li > a").html());

Or, as Reigel suggests, with an anonymous function to the .html() method (I wrote my answer rather quickly and, obviously, unthoughtfully):

$("li > a").html(function (idx, html) {
    return "<span>" + html;
});

Otherwise, it could seem that you want to wrap the contents of the anchor element in a span. In that case, you should instead use one of the jQuery wrapping methods:

$("li > a").wrap("<span>");

You're not meant to create both the starting element and the closing element yourself (when using jQuery).

Sune Rasmussen