Javascript替换父html(删除子)

时间:2017-02-05 09:13:49

标签: javascript

我想在我的页面上循环每个iframes标签并用新的div替换它们并且在途中删除父内容,以便新div将是唯一的子项:

<div id="parent">
   <p>this is parent content</p>
   <iframe src="http://www.example.com" id="iframe10"></iframe>
</div>

结果应该是:

<div id="parent">
   <div id="newdiv">this is new div</div>
</div>

以下是我在页面上循环所有iframe的代码,问题是我不了解如何访问每个iframe父级并删除其内容:

        var i, frames;
        frames = document.getElementsByTagName("iframe");
        for (i = 0; i < frames.length; ++i)
        {           
            frame_id = frames[i].id;
        }

由于 晒

4 个答案:

答案 0 :(得分:1)

var i, frames;
frames = document.getElementsByTagName("iframe");
for (i = frames.length; i; --i) // the array-like object shrinks every time a frame is removed so we have to loop backwards
{           
    //frame_id = frames[i].id;
    // get the parent element
    var parent = frames[i].parentElement;
    // empty it (remove all it's elements)
    while(parent.firstChild)
        parent.removeChild(parent.firstChild);

    // add the new div
    var div = /* create new div */;
    parent.appendChild(div);
}

答案 1 :(得分:1)

你可以写成如下:

&#13;
&#13;
function remove_frames() {
  var i = 0;
  var frames = document.getElementsByTagName("iframe");
  while (frames.length > 0) {
    var f = frames[0];
    var p = f.parentElement;
    if (p) {
      while (p.children.length > 0) {
        p.children[0].remove();
      }
      p.innerHTML = "<div id=\"newdiv" + i + "\">this is new div" + i + "</div>";
      i++; //increase id index
      //p.appendChild(
    }
  }
}
&#13;
  <p><input type="button" value="Execute" onclick="remove_frames()" /></p>

  <div id="parent">
    <p>this is parent content</p>
    <iframe src="http://www.example.com" id="iframe10"></iframe>
  </div>

  <p style="color:#6595ee">This element does not contain any sibling IFrame and must be exist in final result!</p>

  <div id="parent2">
    <p>this is parent2 content...</p>
    <div>another element</div>
    <iframe src="http://www.example.com" id="iframe20"></iframe>
    <p>another element after iframe.</p>
  </div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用parentElement

&#13;
&#13;
var iframes = document.getElementsByTagName("iframe");
iframes[0].parentElement.innerHTML = `<div id="newdiv">this is new div</div>`;
&#13;
<div id="parent">
   <p>this is parent content</p>
   <iframe src="http://www.example.com" id="iframe10"></iframe>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用Node.parentNode获取父级,Node.removeChildElement.innerHTML删除内容。

&#13;
&#13;
var i, frames;
  frames = document.getElementsByTagName("iframe");
  for (i = frames.length-1; i >=0; i--) {
    var frame = frames[i];
    if (frame.parentNode) {
      var parent = frame.parentNode;
      while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
      }
    }

  }
&#13;
<div id="parent">
   <p>this is parent content</p>
   <iframe src="http://www.example.com" id="iframe10"></iframe>
</div>
&#13;
&#13;
&#13;