我想删除所有包含类文章的span标记,并将新的span标记附加到内容
<div class="asd">
<span class="location">Foo</span>
<span class="article">bar</span>
<span class="article">lorem</span>
<span class="article">ipsum</span>
</div>
在javascript中我有一个文字,
var text = "bar lorem ipsum";
我希望javascript在DOM中找到它,如果它在那里,那么从元素中删除span标记并将所有这些标记放在单个span标记中,如下所示
<div class="asd">
<span class="location">Foo</span>
<span class="article">bar lorem ipsum</span>
</div>
非常感谢任何帮助。
答案 0 :(得分:2)
您可以使用jQuery each()
函数,查看下面的更新代码段:
var newHTML ='';
$('.asd span.article').each(function(){
newHTML += $(this).text() + " ";
$(this).remove();
})
$('.asd').append("<span class='article'>"+newHTML+"</span>");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="asd">
<span class="location">Foo</span>
<span class="article">bar</span>
<span class="article">lorem</span>
<span class="article">ipsum</span>
</div>
&#13;
答案 1 :(得分:0)
在这里用jquery检查:
<div class="asd">
<span class="location">Foo</span>
<span class="article">bar</span>
<span class="article">lorem</span>
<span class="article">ipsum</span>
</div>
的js
$(".article").remove();
$(".asd").append('<span class="article">bar lorem ipsum</span>');
希望这会对你有所帮助。
答案 2 :(得分:0)
试试这个.use with each
function jquery .check class name include in array .Is not然后将类名传递给array。
并且还使用eq(0)
(相同类名的第一个元素)
var arr=[];
$('.asd').children('span').each(function(a){
var cls =$(this).attr('class');
if(!arr.includes(cls)){
arr.push(cls);
}
else{
$('.'+cls).eq(0).text($('.'+cls).eq(0).text()+' '+$(this).text())
$(this).remove()
}
})
console.log($('.asd').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="asd">
<span class="location">Foo</span>
<span class="article">bar</span>
<span class="article">lorem</span>
<span class="article">ipsum</span>
</div>