Replace element and preserve attributes
Asked Answered
L

1

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()});
})
Lenient answered 3/12, 2013 at 16:40 Comment(7)
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 $().Sayer
i guess this will give you invalid HTML markup, or i'm wrong?!Knives
@KevinB isn't that what I'm doing above? It seems so since it's preserving the individual html of each span.Lenient
@A.Wolff Not if I'm then moving those elements to a ul, right?Lenient
@jboneca Of the child elements yes, but not the attributes on the span/li.Sayer
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.Caracul
try jsfiddle.net/arunpjohny/JNeb8/1Plotter
A
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;
})
Akerley answered 3/12, 2013 at 16:45 Comment(2)
Like all of us ;) Don't forget to mark the answer as accepted if it suits you. Good learning !Akerley
Had to wait for some time limit before I could accept, cheers!Lenient

© 2022 - 2024 — McMap. All rights reserved.