Reputation: 6843
Let's say I wanted to change all <img>
tags to <iframe>
tags on a page. Could javascript be used for this purpose?
Is there any way to change the actual tag type, or would I have to first delete the <img>
and then create the <iframe>
, if so, how can I make sure that the new tag has the same container as the old tag, etc?
What's the most straightforward and browser friendly way to perform such a substitution?
Upvotes: 7
Views: 5414
Reputation: 1159
You cannot change the type of an html tag name but you can replace them. An easy way to do that is with jQuerys replacewith function.
Upvotes: 1
Reputation: 322502
Although it is more convenient using a library like jQuery
, you can do it with no library like this (replacing the element, not changing the type):
Example: http://jsfiddle.net/BvSvb/
var imgs = document.getElementsByTagName('img');
var i = imgs.length;
var parent;
var iframe = document.createElement( 'iframe' );
var currFrame;
while( i-- ) {
currFrame = iframe.cloneNode( false );
currFrame.setAttribute( 'src', imgs[ i ].getAttribute( 'src' ) );
parent = imgs[ i ].parentNode;
parent.insertBefore( currFrame, imgs[ i ] );
parent.removeChild( imgs[ i ] );
}
Upvotes: 4
Reputation: 117334
There is no way to change a tagName.
You can create a new element and assign the attributes from the old element to the new Element, move the childNodes into it and replace the old element with the new Element.
Upvotes: 1
Reputation: 9269
Using standard interfaces, the type of a DOM element can be set only when that element is created. The closest that you can sensibly achieve in a standard way would be:
If you want to do this, and need help to do so, do ask again.
Upvotes: 3
Reputation: 27886
You can't change the type of a tag, you can only replace them with different tags.
You can copy the contents by setting newElement.innerHTML = oldElement.innerHTML
.
Upvotes: 0