2

I'd like to get the HTML of a DOM element that was dynamically created:

 var titleTag = document.createElement("h4");
 titleTag.innerHTML = 'this is a title';

How can I get the entire DOM element with tags?

<h4>this is a title</h4>
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
Naco
  • 842
  • 7
  • 13
  • 1
    If I `console.log(titleTag)` I get `

    this is a title

    `. Fiddle: https://jsfiddle.net/kc85ntwo/
    – justDan Dec 05 '16 at 23:57
  • 3
    @DanielD That's the console's display formatting, though. Getting it as a Javascript string value is a (slightly) different matter. Try `typeof titleTag` to see this. – lonesomeday Dec 05 '16 at 23:59
  • 1
    Ahh @lonesomeday that makes sense. I figured I had to be missing something there =). Thanks for that! – justDan Dec 06 '16 at 00:00
  • ya that's right in fiddle. in my code, it always showin an empty tag

    . very strange.
    – Naco Dec 06 '16 at 00:02
  • typeof(titleTag) outputs 'Object' – Naco Dec 06 '16 at 00:04
  • 1
    @user3681740 My only guess is that somehow or other you are not actually editing the relevant tag. Can you paste the actual current code at the bottom of your question? – lonesomeday Dec 06 '16 at 00:20

1 Answers1

2

The simple way is with outerHTML. This has historically been frowned upon, because it was custom Internet Explorer functionality that was not in any standards, but it is now widely supported and even in a W3C draft standard.

var HTML = titleTag.outerHTML;
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • I tried this solution, I only get '

    ' without the text inside.
    – Naco Dec 05 '16 at 23:54
  • 1
    `outerHTML` is also referenced in the [HTML spec](https://www.w3.org/TR/html/infrastructure.html), which is a recommendation. – Oriol Dec 06 '16 at 00:02
  • 1
    @Oriol Really? Where? #curious – lonesomeday Dec 06 '16 at 00:06
  • 1
    It's just a mention in [Common infrastructure](https://www.w3.org/TR/html/infrastructure.html) - [Conformance requirements](https://www.w3.org/TR/html/infrastructure.html#conformance-requirements) - [Dependencies](https://www.w3.org/TR/html/infrastructure.html#conformance-requirements-dependencies) - DOM. Just below [event name](https://www.w3.org/TR/html/infrastructure.html#eventdef-global-name) – Oriol Dec 06 '16 at 00:16
  • @Oriol Interesting - it's not *defined* as such. But this is splitting hairs: the point is that we can now use it and not feel worried! – lonesomeday Dec 06 '16 at 00:19