JavaScript – Interacting with a Webpage

JavaScript can interact with the elements (such as paragraphs and divs) in a webpage.

Study the following example and pay attention to “document.getElementById” and “innerHTML”

Modify a paragraph example in w3schools.com

JavaScript can change any aspect of a webpage (change / add / remove content, change styles, change attributes of the elements on the page, etc).

But to do that, JavaScript needs a way to know which part of the page you want to modify.

Here’s a quote from w3schools.com. Read this text and try to understand what it means!

The getElementById Method

The most common way to access an HTML element is to use the id of the element.

In the example above the getElementById method used id=”demo” to find the element.

Click the Try it Yourself link on this page if you didn’t already!

Retrieving User Input

If a user is entering values into an HTML form, JavaScript can retrieve those input values.

Give the <input> element an id attribute, then use the “value” attribute in JavaScript to get the input.

See how the value attribute is used below:

<body>

Your mood: <input id="mood" type="text"><br>
<button onclick="checkMood()">Click Here</button>

<p id="show">Results display here</p>

<script>
function checkMood(){
 var mood = document.getElementById('mood').value;
 var message = "Your mood is: " + mood;
 var show = document.getElementById('show');
 show.innerHTML = message;
}
</script>

</body>

Explanation:

  • mood variable stores the user’s input: JavaScript finds the element with id=’mood’ and then gets the value of that elelment
  • text variable message gets the output text ready
  • show is this HTML element: <p id=”show”></p>
  • The last command replaces the text of the “show” paragraph.