Why is my code not working?
I want to check if the color of the paragraph is white(it is white because of the css) and when it is white i want to change it to black so it is visible
function myFunction() {
if (document.getElementById("lol").style.color === "white") {
document.getElementById("lol").style.color = "black";
}
}
p {
color: white;
}
<button onclick="myFunction()">Try it</button>
<p id="lol">adadada</p>
CodePudding user response:
The element does not have that property because it is defined in the css class. you need to define it inline or with javascript.
function myFunction() {
if (document.getElementById("lol").style.color === "white") {
document.getElementById("lol").style.color = "black";
}
}
p { /* this is useless now */
color: white;
}
<button onclick="myFunction()">Try it</button>
<p id="lol" style="color: white;">adadada</p>
CodePudding user response:
You don't know the color at the time you test because the color is not inline. You need to check the computed style or just use a ternary
function myFunction() {
const lol = document.getElementById("lol");
console.log(window.getComputedStyle(lol, null).color)
// the above is too complicated so why not just change to black if not black?
lol.style.color = lol.style.color === "black" ? "white" : "black";
}
p {
color: white;
}
<button onclick="myFunction()">Try it</button>
<p id="lol">adadada</p>
Better: Toggle the class
function myFunction() {
const lol = document.getElementById("lol");
console.log(lol.classList.contains("white")); // can be used or just toggle
lol.classList.toggle("white")
}
.white {
color: white;
}
<button onclick="myFunction()">Try it</button>
<p id="lol" class="white">adadada</p>