Stop Low Resolution Warning Sign

Section 6: The Document Object Model

Adding & Removing Classes TOP

Tutorial Location: /Pages/Tutorials/Tutorial-Page47/


The DOM

a random text error!

a radom text success!

a random text!

success a random text!

error a random text!

a random success text!

a random text!

a random error text!

        

// const content = document.querySelector("p.error"); // Get classes an element has: // console.log(content.classList); // How to add a class: // content.classList.add("test3"); // How to remove a class: // content.classList.remove("test3"); // ---------------------------------------------------------------- // content.classList.add("success"); // --------------------------------------------------------------------------------------------------------------- // Exercise: /* I want you to query all of these elements and then I want you to cycle through them and I want you to give any tag a class of error where error is inside the text, and I want you to give any tag a class of success where success is inside the text. */ // const paras = document.querySelectorAll("p.demo"); // ------------------------------------------------------------------------------------------------------------------------ // const cycleParas = paras.forEach((p) => { // console.log(p.innerText); // // if we use innerText , if we have an element hidden with style="display: none" it will not output that hidden text. // // So we have to use "textContent" property insted of "innerText" property. // // So "textContent" get's all of the text regardless of whether is hidden or not. // }); // ------------------------------------------------------------------------------------------------------------------------ // const cycleParas = paras.forEach((p) => { // console.log(p.textContent); // }); // ------------------------------------------------------------------------------------------------------------------------ const paras = document.querySelectorAll("p.demo"); const cycleParas = paras.forEach((p) => { if (p.textContent.includes("error")) { p.classList.add("error"); } if (p.textContent.includes("success")) { p.classList.add("success"); } }); // ------------------------------------------------------------------------------------------------------------------------ // How to toggle classes: const title = document.querySelector(".title"); // It give's a class called "test" title.classList.toggle("test"); // If we add this line again , it will remove the class we just created. // title.classList.toggle("test");