Replace element and preserve attributes

只愿长相守 提交于 2019-12-04 03:20:54

问题


The following almost works in replace all instances of span[data-type="yesno"] with lis, but I'd like to also preserve the attributes, classes, etc. Is there a way to carry over the attributes in the same way as the html?

$('span[data-type="yesno"]').replaceWith(function(){
    return $("<li>", {html: $(this).html()});
})

回答1:


You have to loop on your element attributes :

$('span[data-type="yesno"]').replaceWith(function(){
   $li = $("<li>", {html: $(this).html()});
   $.each(this.attributes, function(i, attribute){
        $li.attr(attribute.name, attribute.value);
  });
  return $li;
})


来源:https://stackoverflow.com/questions/20356749/replace-element-and-preserve-attributes

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