Question

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

Was it helpful?

Solution

What you are looking for is .wrapInner()

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

Demo: Fiddle

OTHER TIPS

$(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().

Use .wrap()

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

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top