views:

57

answers:

5

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?

A: 

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.

bemace
Note that although `innerHTML` is widely supported, it is not currently part of any W3C standards. If you want to produce a maximally-portable implementation, `innerHTML` should really be avoided.
Tim
+1  A: 

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.

Dr.Molle
+2  A: 

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:

  • create a new element of the required type
  • copy each attribute from the old element to the new one
  • move each child of the old element to be a child of the new one
  • replace the old element in the DOM tree with the new one

If you want to do this, and need help to do so, do ask again.

Tim
+2  A: 

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.

http://api.jquery.com/replaceWith/

Robert
A: 

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 ] );
}
patrick dw