-2

I have made a Js file where I have generated simple Html code:

var id  = document.getElementById("Id1");
var html = "<div id = 'id2'>This is the text generated from JS</div>";

id.innerHTML = html; 

The id "id1" exists in the HTML file. Now when I try to grab id2 in another function in returns null.

var result = document.getElementById("id2");

The value of variable "result" is showing null.

3
  • 3
    Where is id2 in the code above? also you have capital V for var Commented Mar 22, 2016 at 13:21
  • 1
    I'm having no problems with it whatsoever (jsfiddle). decapitalize the Var keywords and you should be okay. Commented Mar 22, 2016 at 13:31
  • The variable html is contained in div with id2, sorry I forgot to use the code tag Commented Mar 25, 2016 at 10:18

1 Answer 1

0

As @Karl-Henry Martinsson mentioned before me the id is case sensitive. Please make sure you are typing in the correct id names, otherwise your code is correct. Here's a sample code that works.

<!DOCTYPE html>
<html>
<body>

<p>Click the button get the HTML content of the div element with id1.</p>

<button onclick="myFunction()">Try it</button>

<div id='id1'>This is going to change</div>

<script>
function myFunction() {
    var x = "<div id=\"id2\">This is the text generated from JS</div>";
    var y = document.getElementById("id1");
    y.innerHTML = x;
}
</script>

</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.