jQuery - add element after text

蓝咒 提交于 2019-12-12 14:50:57

问题


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?


回答1:


Try .append()

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

fiddle Demo




回答2:


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



回答3:


$('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




回答4:


Try:

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

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



回答5:


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");



回答6:


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




回答7:


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>');



回答8:


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'));



回答9:


Try this:

 var ele = document.querySelector("a.active");
     ele.innerHTML += "<b class="caret"></b>";


来源:https://stackoverflow.com/questions/20630017/jquery-add-element-after-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!