Some more experiments with DOM manipulation.
A lot of interaction involves clicking something like button to make something else do something. So there are 3 things that are required:
- Selecting the clickable element
- Make the clickable element ready by adding an event listener to it.
- Selecting the target element/s
- Writing the code to do the thing you want to do.
So this pages uses tryout-arrays.js
and html-2.js
Basic test
To check this is working
const test = document.getElementById('test');
test.addEventListener('click', function() {
document.body.style.background = 'blue';
document.getElementById('done').innerHTML = '✔ Done (and JS files can contain emoji)';
});
textContent
The paragraph below has it’s text changed using textContent
while the button text uses innerHTML
.
What the difference between innerHTML
and textContent
?
const change = document.getElementById('change-btn');
const paragraph = document.getElementById('text-to-change');
change.addEventListener('click', () => {
paragraph.textContent = 'This uses textContent ... See the code <u>below</u>...';
change.innerHTML = 'Button is <b>impotent</b>';
});
Property | What it does |
---|---|
innerHTML |
changes text between tags allowing new tags to be inserted |
textContent |
changes text between tags. Any new tags are rendered as text. |
innerText |
changes text between tags. Styles are retained. |
The original text wrapped with a span.
querySelectorAll
some text 1
some text 2
some text 3
some text 4
some text 5
classList.toggle
This provides a way to make a click event into a toggle switch. Here a class is added then removed with each click of the button. It doesn’t matter whether the class is present or not on the element to begin with. Whichever it is the first click will change that.
See W3 Schools page
const paragraphs = document.querySelectorAll('.para-g');
const toggle = document.getElementsByClassName('toggle');
toggle[0].addEventListener('click', () => {
alert();
paragraphs[0].classList.toggle('yed');
});
NB. You can also use .classList
with add
or remove
one or more classes.
paragraphs[0].classList.add('class-name-1, cn-2, wrapper');
paragraphs[0].classList.remove('cn-1, cn2');