如何在javascript中找到li标记并替换为另一个li标记



我想找到具有特定id的li,并将其替换为ll标记这是代码。。

var t = document.getElementById('idname').getAttribute('atrname');
$('li.classname').each(function(element) {
if(t == $(this).text()){
$('.classname li').replaceWith('li');
}
});

html

<ul class="classname">
<li id="idname" attrname"name"></li>
</ul>

谢谢。。

如果我正确理解了你的问题,这应该会回答你的问题:

var t = document.getElementById('idname').getAttribute('atrname');
$('li.classname').each(function(element) {
if(t == $(this).text()){
// New LI element with same id as original LI
let newLi = "<li id='someId'>This is new li replacing prev LI with #someId</li>";
// Appending new LI next to original LI and then removing original LI
$('#someId').after(newLi).remove();
}
});

我也创建了一个jsFiddle。如果这有帮助,请告诉我!

最新更新