Referencing Page Elements

For JavaScript functions to modify page elements, it must know how to identify them.

this

this is a reference to the containing element of the event call.

“this” can be passed as an actual parameter from the action event to a function’s formal parameter.

In this example either paragraph will be modified:

function highlight(element) {
    element.style.backgroundColor = "red";
}

function removehightlight(element) {
    element.style.backgroundColor = "white";
}
<p onmouseover="highlight(this)" onmouseout="removehightlight(this)">I am special.</p>
 
<p onmouseover="highlight(this)" onmouseout="removehightlight(this)">So am I.</p>

 

Document Object Model (DOM)

“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”

The getElementById method can be used to access and change the properties of any page element that has an id.

In this example, a hidden paragraph is displayed when a button is clicked.

function showMessage() {
    element = document.getElementById("secretMessage")
	element.style.display="block";
}
<p id="secretMessage" style="display:none;">This is a secret message</p>
 
<button onclick="showMessage()">Show the Message</button>