Accessing HTML 2

Page section: playground

Some more experiments with DOM manipulation.

A lot of interaction involves clicking something like button to make something else do something. So there are 3 things that are required:

  1. Selecting the clickable element
  2. Make the clickable element ready by adding an event listener to it.
  3. Selecting the target element/s
  4. Writing the code to do the thing you want to do.

So this pages uses tryout-arrays.js and html-2.js

Basic test

To check this is working

const test = document.getElementById('test');

test.addEventListener('click', function() {
    document.body.style.background = 'blue';
    document.getElementById('done').innerHTML = '✔ Done (and JS files can contain emoji)';
});

textContent

The paragraph below has it’s text changed using textContent while the button text uses innerHTML.

What the difference between innerHTML and textContent?

const change = document.getElementById('change-btn');
const paragraph = document.getElementById('text-to-change');

change.addEventListener('click', () => {
    paragraph.textContent = 'This uses textContent ... See the code <u>below</u>...';
    change.innerHTML = 'Button is <b>impotent</b>';

});
Property What it does
innerHTML changes text between tags allowing new tags to be inserted
textContent changes text between tags. Any new tags are rendered as text.
innerText changes text between tags. Styles are retained.

The original text wrapped with a span.

querySelectorAll

some text 1

some text 2

some text 3

some text 4

some text 5

classList.toggle

This provides a way to make a click event into a toggle switch. Here a class is added then removed with each click of the button. It doesn’t matter whether the class is present or not on the element to begin with. Whichever it is the first click will change that.

See W3 Schools page

const paragraphs = document.querySelectorAll('.para-g');

const toggle = document.getElementsByClassName('toggle');

toggle[0].addEventListener('click', () => {
    alert();
    paragraphs[0].classList.toggle('yed');
});

NB. You can also use .classList with add or remove one or more classes.

paragraphs[0].classList.add('class-name-1, cn-2, wrapper');
paragraphs[0].classList.remove('cn-1, cn2');
View contents of: /static/js/tryout-arrays.js
const fruit = ["apples", "bananas", "cantaloupe", "dorians"];

const scientificFruit = [
  "Bell pepper",
  " Chile pepper",
  " Corn kernel",
  " Cucumber",
  " Eggplant",
  " Jalapeño",
  " Olive",
  " Pea",
  " Pumpkin",
  " Squash",
  " Tomato",
  " Zucchini",
];

const todos = [
  {
    id: 1,
    text: "Take out rubbish",
    isCompleted: true,
  },
  {
    id: 2,
    text: "Meet with boss",
    isCompleted: true,
  },
  {
    id: 3,
    text: "Dental appointment",
    isCompleted: false,
  },
];

function showFruit() {
  document.getElementById("fruitlist").innerHTML = fruit;
}

function fruitLoops(frt) {
  document.getElementById("fruit-loops").innerHTML += frt + '<br>';
}

const butt1 = document.getElementById("listfruit");

butt1.addEventListener("click", () => {
  document.getElementById("fruitlist").innerHTML = fruit;
});

const butt2 = document.getElementById("fruit2");

butt2.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = fruit[1];
});

const butt3 = document.getElementById("scientific");

butt3.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = scientificFruit;
});

const butt39 = document.getElementById("copying");

butt39.addEventListener("click", function () {
  const otherFruit = fruit.slice(1, 3);
  console.log("what apphen?");
  alert(`A new array called otherFruit now contains ${otherFruit}`);
});

// For buttons showing Array Methods

let myVar = [[1, "tree"], 2, 3, 4, 5, 6];
const mySubVar = ["frog", "Linsang", "stink badger"];

const showMyVar = document.getElementById("show-my-var");
const smvList = document.getElementById("smv-list");

function listMyVar() {
  smvList.innerHTML = ``;
  for (let i = 0; i < myVar.length; i++) {
    smvList.innerHTML += `<li>${myVar[i]}</li>`;
  }
}

showMyVar.addEventListener("click", () => {
  listMyVar();
});

const resetMyVar = document.getElementById("reset-my-var");

resetMyVar.addEventListener("click", () => {
  myVar = [[1, "tree"], 2, 3, 4, 5, 6];
  listMyVar();
  //   alert("reset");
});
View contents of: /static/js/html-2.js
// a variable to store this method
const test = document.getElementById('test');

test.addEventListener('click', function() {
    document.body.style.background = 'blue';
    document.getElementById('done').innerHTML = '✔ Done (and JS files can contain emoji)';
});


const change = document.getElementById('change-btn');
const paragraph = document.getElementById('text-to-change');
const borderBtn = document.getElementById('border-btn');
const getRid = document.getElementById('get-rid');

change.addEventListener('click', () => {
    paragraph.textContent = 'This uses textContent rather than innerHTML. textContent doesn’t allow HTML tags like <u>. See the code <u>below</u> to compare.';
    change.innerHTML = 'Button is <u>impotent</u>';
});

borderBtn.addEventListener('click', () => {
    paragraph.style.border = 'solid 1px cadetblue';
});

// Toggles element but relies on style attribute in paragraph first.

getRid.addEventListener('click', () => {
  paragraph.style.display === "block"
    ? (paragraph.style.display = "none")
    : (paragraph.style.display = "block");
})



// ========= code for querySelectorAll section =======

const paragraphs = document.querySelectorAll('.para-g');

let changeMe = true;

const pinkBorder = () => {
    if (changeMe === true) {  
        paragraphs[4].style.border = 'solid pink 1px';
        paragraphs[4].style.padding = '1em';
        paragraphs[4].innerHTML = 'event listener fails to call this arrow function';
        changeMe = false;
    }
    else {
        paragraphs[4].style.border = 'none';
        paragraphs[4].style.padding = '0';
        paragraphs[4].innerHTML = 'Using <code>onclick</code> instead';
        changeMe = true;
    }
};

const changeBtn = document.querySelector('#change-btn');

// toggles[4].addEventListener('click', () => {
//     alert('ho down');
//     // pinkBorder()
// });


// Comparison

const comparsion = document.getElementById('comparison');

function innerT() {
    comparsion.innerText += 'This uses innerText.';
    console.log(comparsion.innerText);
}

function textC() {
    comparsion.textContent += 'This uses textContent.';
    console.log(comparsion.textContent);
}


// ======= Toggle ============

const toggles = document.getElementsByClassName('toggles');


toggles[0].addEventListener('click', () => {
    paragraphs[0].classList.toggle('yed');
    paragraphs[0].innerHTML = 'changed using classList.toggle';
});

toggles[1].addEventListener('click', () => {
    paragraphs[1].classList.toggle('zed');
    paragraphs[1].innerHTML = 'added the zed class';
});


toggles[2].addEventListener('click', () => {
    if (paragraphs[2].innerHTML != 'whoosh') {
        paragraphs[2].innerHTML = 'whoosh';
    }
    else {
        paragraphs[2].innerHTML = 'some text 3';
        // alert('workd');
    }
});

toggles[3].addEventListener('click', () => {
    paragraphs[3].style.display == 'block' ? paragraphs[3].style.display = 'none' : paragraphs[3].style.display = 'block';
})

Table of Contents