Getting and setting data on a web page with JavaScript | Coding tutorial
text
Manipulating Web Pages with JavaScript
Greetings everyone! Today, we're diving deep into using JavaScript to interact with web pages. Specifically, we're going to learn how to get and set data on a web page using the JavaScript console.
Prerequisites
Before we start our journey, it's crucial to get acquainted with some basics. If you are new to JavaScript or the JavaScript console, make sure to check out the introductory lessons on CLIs earlier in the course.
- Introduction to JavaScript Console
- Basics of HTML Elements
- Working with Developer Tools
Accessing Developer Tools
The first step is to access the developer tools in our browser. The quickest way is to hit F12 on the keyboard. Developer tools give us the power to peer into the underlying HTML structure of web pages.
Within the developer tools, we primarily focus on two tabs:
- Console: for executing JavaScript code
- Elements: to view HTML structure
Interacting with Input Elements
For this demonstration, we'll interact with the search box on the Google search page. To fetch an HTML element using JavaScript, we use the document.getElementById()
method.
let searchBox = document.getElementById("input-element-id");
In the above code snippet, replace input-element-id
with the actual ID of the search box element, which you can find by inspecting the element in the developer tools. Once we have the element, we can access its properties and methods using the dot operator.
Getting and Setting Data
Now, how do we actually read and modify the data inside this search box? Quite simple!
// To get the value
let currentValue = searchBox.value;
// To set the value
searchBox.value = "deeplizard";
Executing the above JavaScript code allows us to read the current text inside the search box and even modify it. How cool is that?
Wrapping Up
There we have it, folks! A real-world example of how to get and set data on web pages using JavaScript. Whether you find this easy or challenging, don't hesitate to hit the comments with your questions. And, of course, make sure to keep following the other lessons of this course.
quiz
resources
updates
Committed by on