MikesEpitaphSays
MikesEpitaphSays

Reputation: 49

navigation li to create <span></span> around text via jquery

I've been trying all day and reading a few things, but for some reason my code isn't working right

What i'm trying to achieve is this: When i create an un ordered list in my index page - I want my jquery to automatically add around the text in the anchor. So i want it to look like this

<li><a href="index.htm"><span>Home</span></a></li>

while I am only adding:

<li><a href="index.htm">Home</a></li>

I want to do this because i have a LOT of list items and instead of writing when i'm adding pages it makes the most sense to save some time in the long run and create a loop that will handle that anytime i add one.

This is What i have so far (sorry if it looks ugly):

$('document').ready(function () {
    var begSpan = "<span>";
    var endSpan = "</span>";
    $('p').each(function () {
        $(this) prepend(begSpan);
    }).append(endSpan);
});

How can i get that to auto create span tags for me

Upvotes: 0

Views: 569

Answers (3)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70159

$(document).ready(function() {
    $('li a').wrapInner('<span/>');
});

Fiddle

.wrapInner() docs

I'd also suggest using a more specific selector (e.g. #menuId li a) for future-proofness.


My original answer used .wrap() which would generate a li > span > a DOM structure, however your requested structure seems to be li > a > span which can be achieved with .wrapInner().

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

What you are looking for is .wrapInner()

$(document).ready(function() {
    $('li a').wrapInner('<span/>');
});

Demo: Fiddle

Upvotes: 2

Use .wrap()

$(document).ready(function() {
    $('li > a').wrap('<span>');
});

DEMO

Upvotes: 1

Related Questions