如何在JavaScript中查找li标签并替换为另一个li标签

时间:2018-10-28 14:32:11

标签: javascript jquery

我想找到具有特定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>

谢谢..

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,这应该可以回答您的问题:

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。 让我知道是否有帮助!

相关问题