4

i have a navigation with some links:

<ul class="nav">
 <li>
  <a class="active">linkname</a>
 <li>
</ul>

now i need to add extra content directly after "linkname" like this:

<ul class="nav">
 <li>
  <a class="active">linkname<b class="caret"></b></a>
 <li>
</ul>

how can i add elements (div,span,b) directly after specific text?

Jim
  • 913
  • 4
  • 16
  • 29

9 Answers9

4

Try .append()

$('ul.nav a.active').append('<b class="caret"></b>');

fiddle Demo

Tushar Gupta - curioustushar
  • 56,454
  • 22
  • 99
  • 107
1
$('a.active').html($('a.active').text() + '<b class="caret"></b>');

Updates:

Wonder if this question to be like how to insert an element inbetween the text

<a class="active">link<b class="caret">BOLD</b>name</a>

So I tried like

String.prototype.splice = function (idx, rem, s) {
    return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};

var text = $('a.active').text();
var ind = text.indexOf('name'); //specify where to add the text
var result = text.splice(ind, 0, '<b class="caret">BOLD</b>');
$('a.active').html(result);

Got this protoype splice from @user113716's answer.

JSFiddle

Community
  • 1
  • 1
Praveen
  • 53,079
  • 32
  • 129
  • 156
1
$("a.active").append("<b class='caret'></b>");
Krish R
  • 22,188
  • 7
  • 49
  • 57
0

Try:

append() inserts content to the end of each element in the set of matched elements.

$(".nav .active").append("<b class='caret'></b>");
codingrose
  • 15,345
  • 11
  • 37
  • 58
0

you can work with .append()

like:

<ul class="nav">
  <li>
    <a id="myelement" class="active">linkname<b class="caret"></b></a>
  <li>
</ul>

javascript:

$("#myelement").append("whatever you want to add after linkname");
Black Ops
  • 356
  • 2
  • 15
0

Try .html() and replace if you need to add the element specifically after a text like linkname

$('.active').html(function(){
  return this.innerHTML.replace("linkname","linkname" + '<b class="caret"></b>');
});

DEMO

Anton
  • 31,487
  • 5
  • 43
  • 54
0

You can use append like this:

$('a.active').append('<b class="caret"></b>');

Or like this:

var b = '<b class="caret"></b>';
var a = $('a.active');
b.appendTo(a);

Or like this:

$('a.active').append($('b.caret'));
Bhojendra Rauniyar
  • 78,842
  • 31
  • 152
  • 211
0

A quick test shows that this should do the job:

var c = '<b class="caret"></b>';
$(".active").append(c);

or as a oneliner ...

$(".active").append('<b class="caret"></b>');
Chris J
  • 29,695
  • 5
  • 65
  • 106
0

Try this:

 var ele = document.querySelector("a.active");
     ele.innerHTML += "<b class="caret"></b>";
Mr.G
  • 3,253
  • 2
  • 15
  • 20
  • 2
    This is wrong. your code will create `b` tag after `a`, not within `a`. Refer [.after()](http://api.jquery.com/after/) and the result for your code will be `linkname` – Praveen Dec 17 '13 at 09:18