HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)
26 - Changing, Adding and Deleting Elements
Updating Content in Elements
Use the innerHTML property to change content or insert new content between element tags. It can be used on any element. To change content, set the innerHTML property to the desired string. To do this, we must use the equals symbol (=). To remove content, set it to an empty string.
element.innerHTML = new html content |
Change the inner HTML of an element |
element.attribute = new value |
Change the attribute value of an HTML element |
element.setAttribute(attribute, value) |
Change the attribute value of an HTML element |
element.style.property = new style |
Change the style of an HTML element |
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="demo" onclick="myFunction()">Click me</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Using JavaScript is super fun!";
}
</script>
</body>
</html>
Adding and Deleting Elements
Make elements, like images, appear on screen with the document object’s createElement method. Add the element to the screen using the appendChild() method.
document.createElement(element) |
Create an HTML element |
document.removeChild(element) |
Remove an HTML element |
document.appendChild(element) |
Add an HTML element |
document.replaceChild(element) |
Replace an HTML element |
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="demo"></p>
<button onclick="show_image ('cat.jpg',200,150,'cats');">
Display an image!
</button>
<script>
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
</script>
</body>
</html>