Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace element and preserve attributes

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()});
})
like image 536
emsoff Avatar asked Dec 03 '13 16:12

emsoff


1 Answers

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;
})
like image 183
OlivierH Avatar answered Sep 19 '22 00:09

OlivierH