DOM Note
DOM Note
Selecting
- getElementById:
document.getElementById(‘banner’)
- getElementsByTagName: (all the passages or anchor tag or img)
document.getElementsByTagName('p')
- getElementsByClassName
const squareImage = document.getElementsByClassName('square')
3. querySelectorAll
document.querySelector('input’)[1]
5. Attributes
- document.querySelector('#banner').id = 'whoop'
—> Changing ID make the attribute different also because it is set
in CSS
- .getAttribute(‘id’ / ‘class’/ ‘tittle’) or .setAttribute(‘tittle’,
‘chicken’) to change
- Changing Style:
const h1 = document.querySelector('h1')
h1.style.color = ‘aqua’
- Class List :
h2.classList.add(‘purple’) to add another class to the current one
h2.classList.toggle(‘purple’): to turn on/off the attribute
paragraph.children[0]
- Example: Create a H3, add content and add H3 into the body
const newH3 = document.createElement('h3')
newH3.innerText = 'I am new! '
document.body.appendChild(newH3)
EVENTS
1. Inline event
2. Onclick property :
document.querySelector('h1').onclick = function(){
alert('You clicked the h1')
}
3. AddEventListener
Example 1:
const btn3 = document.querySelector('#v3');
btn3.addEventListener('click', () => {
alert('CLICKED!')
})
Example 2:
const makeRandColor = () => {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
return `rgb(${r}, ${g}, ${b})`;
}
4. This
const buttons = document.querySelectorAll('button');
for (let button of buttons) {
button.addEventListener('click', colorize)
}
function colorize() {
this.style.backgroundColor = makeRandColor();
this.style.color = makeRandColor();
console.log(this)
}
5. Event Object
input.addEventListener('keydown', function(e){
console.log(e.key) —> It varies based on the language
console.log(e.code) —> Actually on the keyboard
})