如何获取从javascript生成的HTML元素的id
我制作了一个Js文件,其中生成了简单的Html代码:如何获取从javascript生成的HTML元素的id,javascript,Javascript,我制作了一个Js文件,其中生成了简单的Html代码: var id = document.getElementById("Id1"); var html = "<div id = 'id2'>This is the text generated from JS</div>"; id.innerHTML = html; 变量“result”的值显示为null。正如@Karl Henry Martinsson在我前面提到的,id区分大小写。请确保您键入的id名称正确,
var id = document.getElementById("Id1");
var html = "<div id = 'id2'>This is the text generated from JS</div>";
id.innerHTML = html;
变量“result”的值显示为null。正如@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>
单击按钮获取id1的div元素的HTML内容
试试看
这将会改变
函数myFunction(){
var x=“这是从JS生成的文本”;
var y=document.getElementById(“id1”);
y、 innerHTML=x;
}
上面代码中的
id2
在哪里?此外,您还有var
的大写V,我对此没有任何问题。去掉Var
关键字的首字母,你应该会没事的。变量html包含在div中,带有id2,很抱歉我忘了使用代码标签
<!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>