2

In the mozill api docs for outerHTML is stated, that when seeting outerHTML:

Replaces the element with the nodes generated by parsing the string content with the parent of element as the context node for the fragment parsing algorithm.

However, when I tried this in the console it didnt work:

var d = document.createElement('div')
d.outerHTML = '<p>Some Text</p>'
console.log(d) //<div>

Can someone explain to me why this isnt working as expected?

// EDIT: Accoring to comments I should append it to a rendering context. The following still not work for me:

var d = document.createElement('div')
document.body.appendChild(d)
d.outerHTML = '<p>Some Text</p>'
console.log(d) //<div>

// EDIT2: Looking at the generated source, the element indeed gets replaced. However, d is still a div. Well - thats confusing. Why is that so?

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60
  • 2
    Because there is no parent element to provide a parsing context. – Alex K. Jul 11 '17 at 14:08
  • I thought that too, so I tried that example but with the additional line `document.body.appendChild(d)` - no difference – Fuzzyma Jul 11 '17 at 14:10
  • 1
    did you appendChild before you set outerHTML? - it works for me (Chrome) - https://jsfiddle.net/xhh7vgzb/ – Alex K. Jul 11 '17 at 14:12
  • 1
    Using FF here. I append it directly after creation (edit: not working in chrome, too. Code: `var d = document.createElement('div'); document.body.appendChild(d); d.outerHTML = '

    Some Text

    '; console.log(d); //
    `
    – Fuzzyma Jul 11 '17 at 14:14
  • 1
    As the docs state: "Also, while the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element:" – j08691 Jul 11 '17 at 14:19
  • 1
    guess reading is a useful skill - also in this case. Thanks @j08691. Post it as answer and I will accept it – Fuzzyma Jul 11 '17 at 14:21

1 Answers1

2

The MDN docs has the answer as to why the div element gets replaced and console.log(d) refers to the original div and not the replaced content:

...while the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element...

j08691
  • 204,283
  • 31
  • 260
  • 272
  • To add, you may like to know: how to [`target.replaceWith(element)`] https://stackoverflow.com/questions/843680/how-to-replace-dom-element-in-place-using-javascript – Nor.Z Feb 15 '23 at 09:59