Targetting children
video at 1.27m
document.querySelectorAll('ul')[2].firstElementChild.remove();
document.querySelectorAll('ul')[2].lastElementChild.textContent = 'Howdie';
document.querySelectorAll('ul')[2].children[2].innerText = 'Bonjour';
Add users
Adding an event listener to a submit and target to refer to the element that is clicked.
The code
First several querySelectors have been used to select the elements needed.
The default of a submit input is to send something to a server. So the e.preventDefault(); stops that.
Next an if statement checks that both fields have been filled in. If not a message appears but disappears again after 3 seconds.
When both field have been filled in the function first creates a new list item (li). This has a new text node added with the text collected from the form: nameInput.value and emailInput.value. This is then added (appended) to the ul with the id of users.
After this the form is cleared by assigning the variable values an empty string: nameInput.value = '';.
function onSubmit(e) {
e.preventDefault();
if(nameInput.value === '' || emailInput.value === '') {
msg.innerHTML = 'Please enter both fields';
setTimeout(() => msg.remove(), 3000);
}
else {
const liMaker = document.createElement('li');
liMaker.appendChild(document.createTextNode(`${nameInput.value} : ${emailInput.value}`))
users.appendChild(liMaker);
// clear fields ready for another input.
nameInput.value = '';
emailInput.value = '';
};
}
Using target
The target property refers to itself. The target is the button with the id of ibtn
const iBtn = document.getElementById('ibtn');
iBtn.addEventListener('click', (e) => {
e.preventDefault();
console.clear();
console.log(e.target);
alert('no ' + e.target);
})
Adding classes
Adding and removing classes with classList.
document.querySelector('#name').classList.add('dark');
document.querySelector('#name').classList.remove('dark');
Using attribute selectors
This is similar to CSS but you have to use quotes around the attribute value.
const submit = document.querySelector('input[type="submit"]');
Having this makes it easy to change what the submit button says:
submit.value = 'sent';
Events
Events can be added in JavaScript using addEventListenter('event')
clicksubmitmouseout
HTML Events
HTML events are added as attributes to HTML tags.
Note they all begin with on and they’re all lower case.
| HTML attribute | what triggers it |
|---|---|
| onchange | An HTML element has been changed |
| onclick | The user clicks an HTML element |
| onmouseover | The user moves the mouse over an HTML element |
| onmouseout | The user moves the mouse away from an HTML element |
| onkeydown | The user pushes a keyboard key |
| onload | The browser has finished loading the page |