Locating and Accessing Elements - HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

24 - Locating and Accessing Elements

We can access objects in the DOM using an element’s ID.

To do so, we can use the document object’s getElementById() method. This means that the element must have an ID. Using this method allows you to manipulate the contents of that element.

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<p id="demo">Click the button to change the text in this paragraph.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction() {

document.getElementById("demo").innerHTML = "Hello World";

}

</script>

</body>

</html>

Other methods

- Finding elements by id

- Finding elements by tag name

- Finding elements by class name

- Finding elements by CSS selectors

- Finding elements by HTML object collections