如何获取从javascript生成的HTML元素的id

时间:2016-03-22 13:19:40

标签: javascript

我制作了一个Js文件,我生成了简单的Html代码:

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

id.innerHTML = html; 

id&#34; id1&#34;存在于HTML文件中。 现在当我尝试在另一个函数中获取id2时返回null。

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

变量&#34;结果&#34;的值显示为空。

1 个答案:

答案 0 :(得分:0)

正如@ Karl-Henry Martinsson在我之前提到的那样,id是区分大小写的。请确保输入正确的ID名称,否则您的代码是正确的。这是一个有效的示例代码。

<!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>