I wanted to make a list of elements that has the functionality that if you click a list element its text turns red. I then wanted to make a button that would set all the elements in the list to black. However, the button only makes the list elements that have not been clicked, to black. The newly red items are unaffected.
<ul id="outerUl" style="color:pink">
<li>First item in list</li>
<li>Second item in list</li>
</ul>
<input type="submit" onclick="clearListColour()">
And the JavaScript:
<script>
var textColourChanger = function(e){
e.target.style.color = 'red';
}
function clearListColour(){
document.getElementById('outerUl').style.color = 'black';
}
document.getElementById('outerUl').addEventListener('click', textColourChanger);
When you hit the button, you can see in inspect that the color of the ul is set to black, but it doesn't seem to be able to make it in an li that has had it colour set by clicking.
The button you created sets 'color' attribute in <ul> element, so it will affect every element that is inside of <ul>
To overwrite the color from <ul> you need to set the color directly in <li> element
To achieve the effect of changing the color of only clicked <li> item, you would need to addEventListener to specific <li> items, so whenever one of them is clicked, its font color changes. To reset them all to black you'd have to do the same, change all of their font colors back to black, or manipulate css with !important flag on <ul> color.
Add ids to your <li> items like so <li id="li1"> <li id="li2">
addEventListeners to them by Id and you should be good to go
more easy if you use some css:
const
outerUl = document.getElementById('outerUl')
, BtClear = document.getElementById('bt-clearList')
;
outerUl.onclick = e =>
{
if (!e.target.matches('li')) return
e.target.classList.add('onRed')
}
BtClear.onclick = e =>
{
outerUl.querySelectorAll('li.onRed').forEach(LI=>LI.classList.remove('onRed'))
}
#outerUl li {
color : pink;
cursor : pointer;
}
#outerUl li.onRed {
color : red;
}
<ul id="outerUl">
<li>First item in list</li>
<li>Second item in list</li>
</ul>
<button id="bt-clearList"> Clear List Colours</button>