Skip to content

Instantly share code, notes, and snippets.

@guillaumecabanel
Last active February 14, 2023 12:52
Show Gist options
  • Save guillaumecabanel/bfee751c823a56baceac838afc27e032 to your computer and use it in GitHub Desktop.
Save guillaumecabanel/bfee751c823a56baceac838afc27e032 to your computer and use it in GitHub Desktop.
js recap

DOM & Events: recap

How to get one element from the dom

generic with css selector

<div class="title">Hello</div>
const title = document.querySelector('.title');

if we have an id

<div id="footer">Bye</div>
const footer = document.getElementById('footer').innerText;

With one DOM ELEMENT we can:

  • append html
element.insertAdjacentHTML(['beforebegin', 'afterbegin', 'beforeend', 'afterend'], 'some HTML with <tag> if we want.');
  • get the content inside the element
<div class="title">Hello <strong>world</strong></div>
const element = document.querySelector('.title');

// only text
element.innerText; // => Hello world

// with HTML tags
element.innerHTML; // => Hello <strong>world</strong>
  • replace the content inside the element
// only text
element.innerText = 'some text';

// with HTML tags
element.innerHTML = 'some <strong>text</strong>';
  • remove one element (remove not hide)
element.remove();
  • get the style of one element
element.style.backGroundColor; // '#234568'
// style css in lowerCamelCase
  • edit the style of one element
element.style.backGroundColor = '#00FF33';
// style css in lowerCamelCase
  • add a class to one element
element.classList.add('active'); // NO `.` IN THE NAME OF THE CLASS!!!
  • remove a class to one element
element.classList.remove('active');
  • toggle a class to one element
element.classList.toggle('active');
  • get the value of an input
<input id="email" type="email" value="[email protected]">
const email = document.getElementById('email');
email.value
  • write the value of an input
email.value = '[email protected]';
  • add an event listener
element.addEventListener('click', (event) => {
  // Callback: this code will be executed asynchronously when (if) event occurs
});

How to get multiple elements from the dom

<ul>
  <li>Banana</li>
  <li>Apple</li>
  <li>Peach</li>
  <li>Pear</li>
</ul>
const fruits = document.querySelectorAll('li'); // NODE LIST <=> Array

With multiple DOM ELEMENTS (NODE LIST) we can:

fruits.forEach((fruit) => {
  // Here we can do anything on ONE DOM element, cf. above.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment