2

I have:

<li class="active"><a href="/">Start</a></li>

How to do in jquery adding new element:

<li class="active"><a href="/"><em><span>Start</span></em></a></li>

I need to add <em><span> </span></em>

  • 2
    [jQuery Select and wrap textNode](http://stackoverflow.com/questions/5291703/jquery-select-and-wrap-textnode) – Andreas Dec 13 '13 at 11:31
  • Give [KnockoutJS](http://knockoutjs.com/) a look as well. Doing DOM manipulation is quick and dirty, but if you're wanting to build a more maintainable code base then switching to a MVVM structure will help by making it so you don't have to rewrite your code everytime you change your markup, and vice versa. – Jim Yarbro Dec 13 '13 at 11:44

5 Answers5

6

You can use .wrapInner() to un-obstructively insert new tags within an existing DOM element

$('.active a').wrapInner('<em><span></span></em>');

Fiddle: http://jsfiddle.net/az8PA/

MackieeE
  • 11,751
  • 4
  • 39
  • 56
0

Try This:

$('li.active a').each(function () {
$(this).wrapInner('<em><span></span></em>');
});

Working Fiddle

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0
$('li.active a').each(function () {
    var text = $(this).text();
    $(this).html('<em><span>' + text + '</span></em>');
});
AfromanJ
  • 3,922
  • 3
  • 17
  • 33
0

Try This:

<li class="active"><a href="/" id="sample">Start</a></li>

    $("#sample").empty();
    $("#sample").append('<em><span>Start</span>');

now you got following:

<li class="active"><a href="/"><em><span>Start</span></em></a></li>
Mr.G
  • 3,413
  • 2
  • 16
  • 20
0

jsfiddle: http://jsfiddle.net/66SRN/

$('li a').wrapInner('<em><span></span></em>');
patel.milanb
  • 5,822
  • 15
  • 56
  • 92