用outerHTML替换元素并立即访问新创建的元素

时间:2015-07-21 22:47:54

标签: javascript html dom

我正在用outerHTML替换其内容来替换DOM元素。这个技巧有效,但我需要立即访问新创建的DOM元素。

不幸的是,元素<x>的创建和var code内容的生成不在我的控制之下。

&#13;
&#13;
var code, e;

(function () {
  /**
   * Things done inside this IIFE is not under my control
   */
  code =
    '<div style="border: 1px solid black;">' +
    '  <span>I </span>' +
    '  <span>want </span>' +
    '  <span>to </span>' +
    '  <span>access </span>' +
    '  <span>all </span>' +
    '  <span>these </span>' +
    '  <span>spans.</span>' +
    '</div>';
  e = document.getElementById('replace_this');
}());

e.outerHTML = code;

// by this point, element e is replaced with newly added HTML. Let's do
// an alert to make sure
alert('Check the document. New HTML is rendered.');

var spans = e.getElementsByTagName('span'); // oops! empty collection
alert(spans.length); // alerts 0
alert(e.outerHTML); // alerts '<x></x>'
&#13;
<div id="container" style="padding: 20px; border: 1px dashed grey;">
  <div>Don't replace this.</div>
  <x id="replace_this"></x>
  <div>Don't replace this either.</div>
</div>
&#13;
&#13;
&#13;

MDN's notes on outerHTML中解释了这种行为:

  

此外,虽然元素将在文档中被替换,但设置了outerHTML属性的变量仍将保留对原始元素的引用

所以我的问题是,在更换旧元素后如何立即访问新添加的元素?

PS:如果有另外一种方法可以用来替换元素然后访问新创建的元素,我准备放弃outerHTML

3 个答案:

答案 0 :(得分:3)

最后,我决定使用insertAdjacentHTML在之前插入新元素,通过调用previousSibling获取新元素,然后使用{{3}删除不必要的元素} . parentElement

var code, e;

(function () {
  /**
   * Things done inside this IIFE is not under my control
   */
  code =
    '<div style="border: 1px solid black;">' +
    '  <span>I </span>' +
    '  <span>want </span>' +
    '  <span>to </span>' +
    '  <span>access </span>' +
    '  <span>all </span>' +
    '  <span>these </span>' +
    '  <span>spans.</span>' +
    '</div>';
  e = document.getElementById('replace_this');
}());

// insert the new element just before <x>
e.insertAdjacentHTML('beforeBegin', code);
// now <x>'s previousSibling should be the newly added element
var new_elem = e.previousSibling;
// get rid of <x>
e.parentElement.removeChild(e);

// by this point, element e is replaced with newly added HTML. Let's do
// an alert to make sure
alert('Check the document. New HTML is rendered.');

var spans = new_elem.getElementsByTagName('span'); 
alert(spans.length); // alerts 7
alert(new_elem.outerHTML); // alerts contents of new element
<div id="container" style="padding: 20px; border: 1px dashed grey;">
  <div>Don't replace this.</div>
  <x id="replace_this"></x>
  <div>Don't replace this either.</div>
</div>

答案 1 :(得分:1)

为什么不给生成的div一个id?然后你可以在新元素上获得getElementById。

例如。

var code =
    '<div id="newElement" style="border: 1px solid black;">' +
    '  <span>I </span>' +
    '  <span>want </span>' +
    '  <span>to </span>' +
    '  <span>access </span>' +
    '  <span>all </span>' +
    '  <span>these </span>' +
    '  <span>spans.</span>' +
    '</div>';

var e = document.createElement('x');
document.getElementById('container').appendChild(e);
e.outerHTML = code;

// by this point, element e is replaced with newly added HTML. Let's do
// an alert to make sure
alert('Check the document. New HTML is rendered.');

e = getElementById('newElement'); // reassign e to the new div
var spans = e.getElementsByTagName('span'); 
alert(spans.length);
alert(e.outerHTML);

答案 2 :(得分:1)

我设法使用以下javascript完成了它:

var code =
    '<div style="border: 1px solid black;">' +
    '  <span>I </span>' +
    '  <span>want </span>' +
    '  <span>to </span>' +
    '  <span>access </span>' +
    '  <span>all </span>' +
    '  <span>these </span>' +
    '  <span>spans.</span>' +
    '</div>';

var e = document.createElement('x');

document.getElementById('container').appendChild(e);

e.outerHTML = code;

var spans = e.getElementsByTagName('span'); // oops! empty collection

这些是我的更改:

/**
 * Return direct children elements.
 *
 * @param {HTMLElement}
 * @return {Array}
 */
function elementChildren(element) {
    var childNodes = element.childNodes,
        children = [],
        i = childNodes.length;

    while (i--) {
        if (childNodes[i].nodeType == 1) {
            children.unshift(childNodes[i]);
        }
    }

    return children;
}
var target = document.getElementById('container');
alert(elementChildren(target)[0].children.length);

for (var i = 0; i < elementChildren(target)[0].children.length; i++) {
    elementChildren(target)[0].children[i].style.border = '1px red solid';
    alert(elementChildren(target)[0].children[i].innerHTML);
}

<div id="container" style="padding: 20px; border: 1px dashed grey;"></div>

以下是包含代码的Codepen,您可以使用它来编辑游戏:http://codepen.io/nicholasabrams/pen/VLGMgj