All the examples i found online didn't work for me. All i want is to change color on text when mouse is on it. And when move mouse to get old color (and maybe to change size, but if that is too complicated not yet) I know how to do that in CSS but i am learning JS and thats the way i would like it. It is only one word in text so it is Class and not ID.
document.getElementsByClassName("akcija").addEventListener("mouseover", mouseOver); document.getElementsByClassName("akcija").addEventListener("mouseout", mouseOut); function mouseOver() { document.getElementsByClassName('akcija').style.color = "black"; } function mouseOut() { document.getElementsByClassName('akcija').style.color = "Blue"; }
<div class="akcija" style="width:200px; height:200px"></div>
document.getElementsByClassName
method returns a nodeList
, so, you can access a DOM
element using its index (zero-based).
Try this:
document.getElementsByClassName('akcija')[0].style.color = "black";
If you are using ES6
you could do this using Array.from
method.
Array.from(document.getElementsByClassName('akcija')).forEach(function(element) {
element.addEventListener('mouseover', mouseOver);
});
Correct code implement IMHO
var akcjijas = document.getElementsByClassName("akcija"); for (var i in akcjijas) { if (akcjijas.hasOwnProperty(i)){ akcjijas[i].addEventListener("mouseover", mouseOver); akcjijas[i].addEventListener("mouseout", mouseOut); } } function mouseOver() { this.style.color = "black"; } function mouseOut() { this.style.color = "Blue"; }
<div class="akcija" style="width:200px; height:100px;background-color: yellow">Akcija</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.