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
  • 923
  • 4
  • 17
  • 30

9 Answers9

4

Try .append()

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

fiddle Demo

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 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
  • 55,303
  • 33
  • 133
  • 164
1
$("a.active").append("<b class='caret'></b>");
Krish R
  • 22,583
  • 7
  • 50
  • 59
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,563
  • 11
  • 39
  • 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
  • 384
  • 2
  • 16
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
  • 32,245
  • 5
  • 44
  • 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
  • 83,432
  • 35
  • 168
  • 231
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
  • 30,688
  • 6
  • 69
  • 111
0

Try this:

 var ele = document.querySelector("a.active");
     ele.innerHTML += "<b class="caret"></b>";
Mr.G
  • 3,413
  • 2
  • 16
  • 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