1

Below is a code snippet

var pTags=document.getElementsByTagName('p');
for(i=0;i<pTags.length;i++)
{
    var p=pTags[i],  div=document.createElement('div');
    div.innerHTML='P tag replaced with a div tag';
    p.parentNode.replaceChild(div, p);
}

It should replace all P tags with Div but it's not replacing all but some of them. The red ones (fiddle) are not replacing.

I don't need this but I want to know what is I'm doing wrong here ? So, my question is why not it's working in this way. Hope someone can tell me the fact.

Thanks for your effort!

4

2 回答 2

4

getElementsByTagName返回一个活动节点列表,因此每次替换节点时列表都会更改,因此您只想获取列表中的第一个节点并替换它,直到列表为空,请参阅http://jsfiddle.net/mowglisanu/eZNqn/ 4/

于 2012-11-15T02:24:35.897 回答
3

单线方式;-)

首先,选择你想要的任何元素(在这种情况下,正文的所有内容)

var elem = document.getElementsByTagName('body')[0];
var target = elem.innerHTML;

“线”

elem.innerHTML = target.replace(/(<div)/igm, '<p').replace(/<\/div>/igm, '</p>');

我希望这会有所帮助。在此处查看实际操作

于 2013-06-06T15:46:49.190 回答