9

I am wondering if its possible to change a HTML elements data type with javascript?

For example change an img to a div? The reason I am doing this & not destroying the img & creating a div is because the element contains A LOT of inline styling so I would need to copy all the inline style from the img to the div. PS: this website is only for iPad, so cross-browser compatibility is not an issue.

var div  = img.cloneNode(true);
div.type = "div";

So it would be easier to clone the node/element using img.cloneNode(true), then must change the type to a div. I hope this is possible?

If not maybe there is a easy way to copy one elements style to another elements? Maybe...

// img is an img HTML element
var div = document.createElement("div");
div.style = img.style;
document.body.removeChild(img); // does that destroy div.style aswell?
isherwood
  • 58,414
  • 16
  • 114
  • 157
sazr
  • 24,984
  • 66
  • 194
  • 362
  • 2
    You can't change an element from one "type" to another, but you can copy the style property from one to the other to copy the inline style. However, the effect may not be the same. – RobG Jan 04 '12 at 02:56
  • Maybe you could hold the contents of the div in a temporary variable, remove the div and then insert the element you want with the content of the temp variable. – Kamal Jun 06 '20 at 18:46

2 Answers2

3

You cannot change the type of an element. Yes, the div's style will be overwritten unless you concatenate div.style+=img.style. In this case like img style attributes override the div's.

ron tornambe
  • 10,452
  • 7
  • 33
  • 60
2

I'd try the second manner - I'd think it should work, and it should be super quick to try it out - probably quicker than asking on here was!

Edit: I can confirm it does NOT work (at least, not in Opera). JSFiddle at http://jsfiddle.net/T7r5c/

SpoonNZ
  • 3,780
  • 1
  • 20
  • 25
  • 1
    http://jsfiddle.net/T7r5c/1/ `elem.style.cssText` is what you were after. But inline-css is evil. Just give the two elements a common class or common selector. – Zirak Jan 04 '12 at 03:02
  • Just posted that answer when I saw your comment. I deleted by answer. – Sandro Jan 04 '12 at 03:06
  • Agree inline css is bad. Perhaps your method, PLUS copy the classes would be the best bet. Depends on the site. Other option might be to loop through the .style object and apply each style individually. Messy though :S – SpoonNZ Jan 04 '12 at 03:08