3. Get HTML element
getElementByID
getElementByTagName
<body>
<img id=“img1” src=“img1.png” alt=“first image”/>
<img id=“img2” src=“img2.png” alt=“second image”/>
<img id=“img3” src=“img3.png” alt=“third image”/>
</body>
document.getElementById(“img1”);
document.getElementByTagName(“img”)[0];
4. Update the HTML Element
Use innerHTML property to update
<head>
<script type="text/javascript">
function updateText()
{
document.getElementById("text").innerHTML = "Hello, JS world!";
}
</script>
</head>
<body>
<p id="text" onclick="updateText();"> Hello, world!</p>
</body>
Output: Hello, world! -> Hello, JS world!
5. DOM
DOM(document object model) is a
concept to organize our html as a tree-
like structure
document
html
<head> …</head>
<body> head body
<p id="text"> Hello, world!</p>
</body> p
Hello, world!
6. DOM
Every block is a node
Upper node is the parent of lower node
Two types of node document
Element
html
Text
Parent of head/body head body
Child of html p
Hello, world!
7. DOM
Some properties to describe nodes
nodeValue
nodeType
document
childNode
html
fisrtChild
lastChild head body
p
Id=textId Hello, world
!
alert(document.getElementById("textId").firstChild.nodeValue);
8. DOM
Some functions to operate nodes
removeChild();
createTextNode();
appendChild();
We use DOM to implement the
aforementioned updateText() function
9. DOM
Use innerHTML
document.getElementById("text").innerHTML = "Hello, JS world!";
Use DOM
while(node.firstChild)
node.removeChild(node.firstChild);
var new_node = document.createTextNode("Hello, JS world!");
node.appendChild(new_node);
Output: Hello, world! -> Hello, JS world!