开发者

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 s开发者_如何学Goo, 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?


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


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜