0

Hello I am kind of stuck right now. I am trying to make my script choose all paragraph inside a div class of change but I don't really understand how to do it. The html looks something like this in the body

<body>
<div id="top" class="change">
<p> Microsoft </p>
<p> Apple </p>
<p> Sony </p>
</div>

<div id="middle">
<p> Disney </p>
<p> Nintendo </p>
<p> Sony </p>
</div>

<div id="bottom" class="change">
<p> Ice</p>
<p> Tea</p>
<p> Water</p>
</div>
</body>

I am trying to make it so when the mouse cursor touches anything that has a class of change in a paragraph, it will change the color to a color of my choice but I don't know how to do it with selectors with pure javascript. This is the current code I have but it is not working. I can only use javascript

var fontChange = document.getElementsByClass("change").getElementsByTagName("p");

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseover=function() {
        this.style.color = "red";
    }
}

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseout=function() {
        this.style.color = "black";
    }
}
Kevin
  • 75
  • 6

2 Answers2

1

There's no function getElementsByClass, it's getElementsByClassName.

document.getElementsByClassName() returns a collection (see What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?), you have to index it to use getElementsByTagName on the elements that it returns.

var fontChange = [];
var change = document.getElementsByClassName("change");
for (var i = 0; i < change.length; i++) {
    var paras = [].slice.call(change[i].getElementsByTagName("p"));
    fontChange.concat(paras);
}

Or you could just use querySelectorAll

var fontChange = document.querySelectorAll(".change p");

You also have a typo. You set the variable fontChange, but then use changeFont in the loop.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can achieve what you want without javascript, just add this code to your css

.change p:hover {
    color: red;
 }
JkAlombro
  • 1,696
  • 1
  • 16
  • 30