Html和javascript提取ID

时间:2016-05-22 15:40:04

标签: javascript html

我无法理解如何一起使用javascript和html。我已设法访问该文件,并从该文件中获取id。但是我只能在使用我想要的id之前定义的id时访问id。有办法解决这个问题吗?

<!DOCTYPE html>
<html lang="en">

<head>

<link href="site.css" rel="stylesheet">

<script src="JavaS.js" async></script>

<title>This is my website</title>

</head>

<body>

<header align="center" id="head01"></header>

<p id="HouseName01"></p>

<p id="HouseAdress03"></p>

<footer id="foot01" align="center"></footer>

</body>
</html>

这是我的HTML代码。

document.getElementById("foot01").innerHTML = "&copy;  " + new Date().getFullYear() + " Dane. All rights reserved.";
document.getElementById("head01").innerHTML = "Dane & Co";

document.getElementById("HouseName01").innerHTML = "House 1 name";
document.getElementById("HouseAdress01").innerHTML = "House 1 adress";
document.getElementById("HouseImage01").setAttribute("src", "C:/Users/currys/Pictures/House01.jpg");

document.getElementById("HouseName02").innerHTML = "House 2 name";
document.getElementById("HouseAdress02").innerHTML = "House 2 adress";

document.getElementById("HouseName03").innerHTML = "House 3 name";
document.getElementById("HouseAdress03").innerHTML = "House 3 adress";

document.getElementById("HouseName04").innerHTML = "House 4 name";
document.getElementById("HouseAdress04").innerHTML = "House 4 adress";

document.getElementById("HouseName05").innerHTML = "House 5 name";
document.getElementById("HouseAdress05").innerHTML = "House 5 adress";

document.getElementById("HouseName06").innerHTML = "House 6 name";
document.getElementById("HouseAdress06").innerHTML = "House 6 adress";

document.getElementById("tempVar").innerHTML = "House22";

这是我的javascript代码。很抱歉没有第一次添加代码。

1 个答案:

答案 0 :(得分:0)

如果要在定义之前获取id为"tempVar"的HTML元素,则不能这样做:

`document.getElementById(<id>)` method is to get existing element identified by its id.

如果要使用js:

创建HTML元素
var newElement = document.createElement("p"); //i.e. <p></p>
var node = document.createTextNode("House22");
newElement.appendChild(node);

稍后您可以在DOM中添加此元素newElement