DOM Manipulation

Exercise 1

Instructions:

See the page here.

HTML (no changes):

<div id="page">
      <h1 id="header">List King</h1>
      <h2>Buy groceries</h2>
      <ul>
        <li id="one" class="hot"><em>fresh</em> figs</li>
        <li id="two" class="hot">pine nuts</li>
        <li id="three" class="hot">honey</li>
        <li id="four">balsamic vinegar</li>
      </ul>
    </div>

Change the text of the first item

//getElementById method
const first = document.getElementById('one')
first.textContent = 'ham'
//querySelector method
const first = document.querySelector('#one')
first.textContent = 'ham'
//querySelectorAll method
const first = document.querySelectorAll('li')[0]

Change the class of the third item to something different (e.g. “cool”, “complete”)

const third = document.querySelector('#three');
//setAttribute method
third.setAttribute('class', 'complete');
//className method
third.className = 'complete'

Change the text of the last item

const list = document.getElementsByTagName('li');
//list gets a nodelist of all the li elements
//console.log(list) returns: [li#one.hot, li#two.hot, li#complete.hot, li#four, one: li#one.hot, two: li#two.hot, complete: li#complete.hot, four: li#four]
//querySelectorAll method:
const list = document.querySelectorAll('li');

const last = list[list.length-1];
//textContent method
last.textContent = 'mayonnaise';
//innerHTML method
last.innerHTML = 'mayonnaise';

Change the class for all items to “cool”

const list = document.getElementsByTagName('li');
//for-of statement
for (const item of list){
  console.log(item);
}
//returns:
      //<li id="one" class="hot">ham</li>
      //<li id="two" class="hot">pine nuts</li>
      //<li id="three" class="complete">honey</li>
      //<li id="four">mayonnaise</li>
      
//for-of statement method
for (const item of list){
   item.setAttribute('class', 'cool');
 }

//sequential for loop method
for (let i = 0; i < list.length; i++) {
  list[i].setAttribute('class', 'cool');
}

Add the number of items in the list to the heading

const groceryCount = document.querySelector('h2');
//join string method
groceryCount.textContent = list.length + ' groceries';
//template literals method
groceryCount.textContent = `${list.length} groceries`;