最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery appendprependwrapInner? - Stack Overflow

programmeradmin1浏览0评论

Intended oute:

<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?

Intended oute:

<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?

Share Improve this question edited Apr 20, 2019 at 18:52 double-beep 5,53719 gold badges40 silver badges49 bronze badges asked Jan 4, 2012 at 19:11 Mr Jonny WoodMr Jonny Wood 3,8545 gold badges31 silver badges42 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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

Something like this should work:

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

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/zqUmL/5/

Is there something wrong with doing this?

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

评论列表(0)

  1. 暂无评论