更改outerHTML

时间:2018-05-10 18:16:38

标签: javascript html dom outerhtml

我想更改一些元素的outerHTML,然后将其传递给一个函数,以便函数可以对它做一些事情:



const bars = document.getElementsByClassName('bar');

for (let i = bars.length - 1; i >= 0; i -= 1) {
  const bar = bars[i];
  bar.outerHTML = `<h1 class="bar">${bar.innerHTML}</h1>`;
  const foo = new Foo(bar);
  // ... some code
  foo.doFoo();
}

function Foo (bar) {
  this.bar = bar;
  this.doFoo = function() {
    this.bar.innerHTML = `Foo${this.bar.innerHTML}`;
    console.log('doFoo:', this.bar.innerHTML);
    // expected on page: "Dog" --> "FooDog", "Turtle" --> "FooTurtle". This doesn't happen.
  }
}
&#13;
<p class="bar">Dog</p>
<p>Cat</p>
<p class="bar">Turtle</p>
&#13;
&#13;
&#13;

然而,虽然在outerHTML发生变化后DOM发生了变化,但变量bar仍在引用&#34; old&#34;元素的(未更改的)版本,当然不再存在于DOM中。因此,无法再更改DOM内容。

MDN上对此行为的说明:

  

虽然元素将在文档中被替换,但是其中的变量   设置的outerHTML属性仍将保持对原始的引用   元件


我怎样才能实现Foo-Object仍然知道DOM中的正确元素,而不必再次查询DOM?

1 个答案:

答案 0 :(得分:0)

一个选项可能是获取对您要更改nextElementSibling的每个outerHTML元素的引用。我们称之为next

然后,在您更新outerHTML后,您将获得对新元素的更新引用:

next.previousElementSibling

或者,实际上,如果您更新的元素已经是最后一个且nextElementSibling已返回undefined

next ? next.previousElementSibling : bar.parentElement.lastChild

&#13;
&#13;
const bars = document.getElementsByClassName('bar');

for (let i = bars.length - 1; i >= 0; i -= 1) {
  const bar = bars[i];
  const next = bar.nextElementSibling;
  
  bar.outerHTML = `<h1 class="bar">${bar.innerHTML}</h1>`;
  
  const foo = new Foo(next.previousElementSibling || next.parentElement.lastChild);
  
  // ...
  
  foo.doFoo();
}

function Foo (bar) {
  this.bar = bar;
  
  this.doFoo = function() {
    this.bar.innerHTML = `Foo${ this.bar.innerHTML }`;
    console.log('doFoo:', this.bar.innerHTML);
    // expected on page: "Dog" --> "FooDog", "Turtle" --> "FooTurtle". This doesn't happen.
  }
}
&#13;
<p class="bar">Dog</p>
<p>Cat</p>
<p class="bar">Turtle</p>
&#13;
&#13;
&#13;