Modifying Elements
Finding and manipulating HTML elements using JavaScript
Referring to elements from JavaScript
Before we can use JavaScript to modify an element,
we need a way to identify it and target it.
Using the get element by id function
In the dev tools Console tab, type this and press enter:
document.getElementById('first-box')
One way to target an element is using its HTML id
,
because an id
should be used only once on a page.
You should see the HTML of first-box
.
Save target elements under given names
In your console, create a variable box
and save first-box
into it
var firstBox = document.getElementById('first-box')
Access a variable by its name
In your console, type box
and press enter.
The firstBox
element should be given back to you.
Modify an element’s content
Using your console, change the text content
inside the first box from frog
to lion
.
box.innerHTML = 'lion'
Modify an element’s CSS
Using your console, change the text colour
of the first box from green
to gold
.
box.css.color = 'gold'
Make your code permanent
The console can only make temporary changes.
Copy the code you’ve learned into your site-script.js
.
var firstBox = document.getElementById('first-box');
firstBox.innerHTML = 'lion'
firstBox.css.color = 'gold';
Do some practice
Use what you’ve learned to:
- Make the second box say ‘tiger’ with an orange background
- Make the third box say ‘elephant’ and upsize to 300px x 300px
Explore your code in real-time
Use debugger
lines in your code to freeze it at any time.
While frozen, you can look at the value in a variable!
var firstBox = document.getElementById('first-box');
firstBox.innerHTML = 'lion'
firstBox.css.color = 'gold';
debugger;
var secondBox = document.getElementById('second-box');
secondBox.innerHTML = 'tiger';
secondBox.css.backgroundColor = 'orange';
What we learned
- Getting an element by its id
- Saving elements to variables
- Modifying an element’s css
- Using debugger break points
Loading...