PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Get Element ById

getElementById

If an element has the id attribute, we can get the element, no matter where it is.
 
// <div id='mydiv'>My content</div>

let el = document.getElementById("mydiv");

console.log(el.innerHTML); // My content

el.style.color = "red";

Global variable

Also, there’s a global variable named by id that references the element. But it is supported mainly for compatibility. Not recommended.
 
// <div id='mydiv'>My content</div>

// let el = document.getElementById("mydiv");

// console.log(el.innerHTML); // My content

mydiv.style.color = "red";
Query Selector    (2/3)

Query selector

querySelectorAll

By far, the most versatile method. This returns the first element for the given CSS selector.
 
// <div class='myClass'>My content</div>

let el = document.querySelector('div.myClass');

console.log(el.innerHTML);
This returns element matching the given CSS selector.
 
/*
<ul>
  <li>The</li> <li>test</li>
</ul>
<ul>
  <li>has</li> <li>passed</li>
</ul>
*/

let elements = document.querySelectorAll('ul > li:last-child');

for (let elem of elements) {
    console.log(elem.innerHTML); // "test", "passed"
}
... 7 lines
 

getElementsByClassName

Today, they are mostly history, as querySelector is more powerful and shorter to write.
 
let el1 = elem.getElementsByTagName(tag);

let el2 = elem.getElementsByClassName(className);
Task     (3/3)

Task

Add .myClass to each li Header. Hint: use querySelector
 
/*
<ul>
  <li>Header A</li>
  <li>Title 1</li>
  <li>Title 2</li>
</ul>
<ul>
  <li>Header B</li>
  <li>Title 1</li>
  <li>Title 2</li>
</ul>

<style>
    .myClass {color: red;}
</style>
*/

// your code here (elements = ?)



// your code END

for (let el of elements) {
    el.classList.add("myClass");
}

Questions    
Css

        A B C D E F
🔔
1/3