Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change a HTML elements type [duplicate]

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?
like image 617
sazr Avatar asked Jan 04 '12 02:01

sazr


People also ask

Can we change HTML tag dynamically?

The easiest way to modify the content of an HTML element is by using the innerHTML property . The innerHTML property gets or sets the HTML or XML markup contained within the element.

How do you repeat the same element in HTML?

Add the repeat-element attribute to the element you want to duplicate and specify the number of times to copy. Use the repeat-text attribute if you only want to duplicate the text within the element.

Can you have duplicate IDs HTML?

Duplicate IDs are common validation errors that may break the accessibility of labels, e.g., form fields, table header cells. To fix the problem, change an ID value if it is used more than once to be sure each is unique.


1 Answers

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.

like image 163
ron tornambe Avatar answered Oct 28 '22 13:10

ron tornambe