I am trying to have an external (not inline) JavaScript code to handle multiple elements depending on their class and id.
My goal is that if an element is of a certain class, its' CSS will change depending on its' id name when it is hovered over.
In this example:
<p class="p-class" id="000">Hi</p>
<p class="p-class" id="FFF">Hi</p>
<p class="p-class" id="FFFF66">Hi</p>
<p class="p-class" id="498F83">Hi</p>
My goal is to get this:
<p class="p-class" id="000" style="color:#000">Hi</p>
<p class="p-class" id="FFF" style="color:#FFF">Hi</p>
<p class="p-class" id="FFFF66" style="color:#FFFF66">Hi</p>
<p class="p-class" id="498F83" style="color:#498F83">Hi</p>
I thought about something in this direction:
const pElements = document.querySelectorAll('.p-class');
for (let i = 0; i < pElements .length; i++) {
pElements[i].addEventListener('mouseover', function() {
pElements[i].style.color = `#${pElements[i].getAttribute('id')`;
});
}
But, I am relatively new to this and I don't know if the above code is valid or how to properly trigger it.
Any insights/suggestions will be highly appreciated!