1

I wrote this script to see how new nodes can be created with createElement():

<!DOCTYPE HTML>
<html>
<head>
<title>DOM Traversal</title>
</head>

<body>

<div>

<p>Sample paragraph</p>
</div>
<h1>Sample H1</h1>

<script>
var p = document.getElementsByTagName("p")[0];
var n = document.createElement("strong");
n.innerHTML = "--LOL--";
p.appendChild(n);
console.log("Done!");

</script>
</body>

</html>

After I load the page, I can see the new node rendered, but it's not there in View Source (in Chrome). Why is this happening?

ankush981
  • 5,159
  • 8
  • 51
  • 96
  • The "View Source" menu tends to only show the source that is downloaded directly from the server. Use the Developer Tools "Inspect Element" to open the page in the DOM inspector and it should show you what you want. – Palpatim Jun 03 '14 at 15:32
  • alert (document.documentElement.innerHTML) –  Jun 03 '14 at 15:41

2 Answers2

7

View source only shows what comes back with the initial http request to the server but it doesn't show the dynamics elements added later.

To those dynamics elements after the initial page load in chrome or other browsers you need to inspect the DOM using the developer toolbar. (In Chrome press F12)

makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76
1

When you use "view source" normally you see the original response from server, before it has been edited by Javascript.

Are you viewing your "--LOL--" text in the page?

If you want to check the source, you should use F12 tools, which updates content.

Jorgeblom
  • 3,330
  • 1
  • 23
  • 24