6

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()});
})
OlivierH
  • 3,875
  • 1
  • 19
  • 32
emsoff
  • 1,585
  • 2
  • 11
  • 16
  • 1
    Yes, but you'll have to iterate over every attribute that you wish to keep and add it to the attribute list that you are passing to `$()`. – Kevin B Dec 03 '13 at 16:41
  • i guess this will give you invalid HTML markup, or i'm wrong?! – A. Wolff Dec 03 '13 at 16:43
  • @KevinB isn't that what I'm doing above? It seems so since it's preserving the individual html of each span. – emsoff Dec 03 '13 at 16:43
  • @A.Wolff Not if I'm then moving those elements to a ul, right? – emsoff Dec 03 '13 at 16:44
  • @jboneca Of the child elements yes, but not the attributes on the span/li. – Kevin B Dec 03 '13 at 16:46
  • If you know the attributes that the span might have (eg, only an id or class) the easiest would be to pass those two attributes together with the html.. If it varies a lot, you will have to iterate through the attributes. – bagonyi Dec 03 '13 at 16:46
  • try http://jsfiddle.net/arunpjohny/JNeb8/1/ – Arun P Johny Dec 03 '13 at 16:47

1 Answers1

13

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;
})
OlivierH
  • 3,875
  • 1
  • 19
  • 32