Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript To Change The Very TYPE Of Tag

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?

like image 830
Joshua Avatar asked Oct 23 '10 17:10

Joshua


People also ask

Can JavaScript change the style of an HTML element?

The HTML DOM allows JavaScript to change the style of HTML elements.

How do I change the text of a tag in JavaScript?

Use the textContent property to change the text of a link element, e.g. link. textContent = 'Replacement link text' . The textContent property will set the text of the link to the provided string, replacing any of the existing content.


1 Answers

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 ] );
}
like image 89
user113716 Avatar answered Oct 21 '22 18:10

user113716