Mr Jonny Wood
Mr Jonny Wood

Reputation: 3854

jquery append / prepend / wrapInner?

Intended outcome:

<li><a><span class="icon"></span><span class="text">Link Text</span></a></li>

Starting html:

<li><a>Link Text</a></li>

I've attempted to use .prepend() with .append() and separately .wrapInner() but neither give the desired output.

$('li a').wrapInner("<span class='icon'></span><span class='text'></span>");

Outputs:

<li><a><span class="icon">Link Text</span></a></li>
$('li a').prepend("<span class='icon'></span><span class='text'>");
$('li a').append("</span>");

Outputs:

<li><a><span class="icon"></span><span class='text'></span>Link Text</a></li>

Is there a way to achieve what I want?

Upvotes: 1

Views: 3630

Answers (4)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

check my jsFiddle here. I used like below,

$('li a').wrapInner("<span class='text'></span>");

$('li a').prepend("<span class='icon'></span>");

If you want in 1 line, then use as below

$('li a').wrapInner("<span class='text'></span>").prepend("<span class='icon'></span>");

DEMO here

Upvotes: 5

Tim
Tim

Reputation: 779

Is there something wrong with doing this?

text = $('li a').html();
$('li a').html("<span class='icon'></span><span class='text'>"+text+"</span>");

Upvotes: 0

Dominic Green
Dominic Green

Reputation: 10258

This seems to work a bit better :)

var curText = $('li a').text();

$('li a').html("<span class='icon'></span><span class='text'>"+curText+"</span>");

http://jsfiddle.net/zqUmL/5/

Upvotes: 0

Matt H
Matt H

Reputation: 6532

Something like this should work:

$('li a').html('<span class="icon"></span><span class="text">' + $('li a').html() + '</span>');

Upvotes: 2

Related Questions