我在简单的代码中,在html页面中使用getelementbyid.innerHtml。请帮我。
<!doctype html>
<html lang="en">
<head>
<title>Dom examples</title>
<script>
var code = document.getElementById("one").innerHTML;
code = code + " !!";
console.log(code);
</script>
</head>
<body>
<h4> DOM practise page </h4>
<p id="one"> This page is for practise of DOM model in JS</p>
<p id="two"> Thank You </p>
</body>
</html>
答案 0 :(得分:0)
在浏览器呈现HTML页面之前调用您的javascript。因此,当您的浏览器呼叫getElementById
时,未定义ID。
只需在文件末尾移动您的JavaScript即可
答案 1 :(得分:0)
只需移动下面的脚本......因为id还没有呈现原因。
<!doctype html>
<html lang="en">
<head>
<title>Dom examples</title>
</head>
<body>
<h4> DOM practise page </h4>
<p id="one"> This page is for practise of DOM model in JS</p>
<p id="two"> Thank You </p>
</body>
<script>
var code = document.getElementById("one").innerHTML;
code = code + " !!";
console.log(code);
</script>
</html>
答案 2 :(得分:0)
利用onload
的{{1}}属性在window
加载时调用函数
window
答案 3 :(得分:0)
只需将脚本部分放在close body之前,它就可以了。
<!doctype html>
<html lang="en">
<head>
<title>Dom examples</title>
<script>
onload = function() {
var code = document.getElementById("one").innerHTML;
code = code + " !!";
console.log(code);
}
</script>
</head>
<body>
<h4> DOM practise page </h4>
<p id="one"> This page is for practise of DOM model in JS</p>
<p id="two"> Thank You </p>
</body>
</html>
答案 4 :(得分:0)
浏览器从上到下解析html页面。因此,如果您将<!doctype html>
<html lang="en">
<head>
<title>Dom examples</title>
</head>
<body>
<h4> DOM practise page </h4>
<p id="one"> This page is for practise of DOM model in JS</p>
<p id="two"> Thank You </p>
<script>
var code = document.getElementById("one").innerHTML;
code = code + " !!";
console.log(code);
</script>
</body>
</html>
放在script
中,它将首先呈现,然后呈现head
。因此,您的body
正在搜索尚未呈现给DOM的ID。
将script
放在底部,可以解决您的问题。
script
答案 5 :(得分:0)
工作正常,最后只使用脚本标签。为了更清晰的检查。 https://jsfiddle.net/djmayank/Lzewxgyw/
HTML
<head>
<title>Dom examples</title>
</head>
<body>
<h4> DOM practise page </h4>
<p id="one"> This page is for practise of DOM model in JS</p>
<p id="two"> Thank You </p>
</body>
JS
var code = document.getElementById("one").innerHTML;
code = code + " !!";
console.log(code);
答案 6 :(得分:0)
在加载id为1的元素之前加载script
,因此尚不存在。{1}}。您有以下选择:
<!doctype html>
<html lang="en">
<head>
<title>Dom examples</title>
</head>
<body>
<h4> DOM practise page </h4>
<p id="one"> This page is for practise of DOM model in JS</p>
<p id="two"> Thank You </p>
<script>
var code = document.getElementById("one").innerHTML;
code = code + " !!";
console.log(code);
</script>
</body>
</html>
function
并使用onload
属性,这是优选的,因为代码可以重复用于其他功能:
<!doctype html>
<html lang="en">
<head>
<title>Dom examples</title>
<script>
function myFunction() {
var code = document.getElementById("one").innerHTML;
code = code + " !!";
console.log(code);
}
</script>
</head>
<body>
<h4> DOM practise page </h4>
<p id="one" onload="myFunction()"> This page is for practise of DOM model in JS</p>
<p id="two"> Thank You </p>
</body>
</html>