0

I am trying to add a class to a child element when the user's mouse moves over the parent. I assumed I could do this by using 'firstChild' but I can't get this to work:

var hoverTrendingBoxContainer = document.querySelectorAll(".trending-box-container");
for (i = 0; i < hoverTrendingBoxContainer.length; i++) {
    hoverTrendingBoxContainer[i].addEventListener("mouseover", function () {
        this.firstChild.classList.add("trending-box-image-hover");
    });
}

This returns 'Cannot read property 'add' of undefined'

Neil

Ele
  • 33,468
  • 7
  • 37
  • 75
  • can you please provide html? – yajiv Mar 10 '18 at 21:27
  • Sounds like a duplicate of [*firstChild returns EmptyTextNode in Edge*](https://stackoverflow.com/questions/34176308/javascript-firstchild-returns-emptytextnode-in-edge), but this happens in other browsers too that preserve whitespace with empty text nodes. Lots of duplicates, e.g. [*Selecting the firstChild and whitespace issue*](https://stackoverflow.com/questions/24907693/selecting-the-firstchild-and-whitespace-issue). Text nodes don't have a *classList* property or method, hence the error. Try *this.children[0].classList.add(...)`. – RobG Mar 10 '18 at 21:27

1 Answers1

0

The reason is that firstChild is text or something else(not any html tag), so you are getting error.

Look at the below example. Here if I mouseover on first div the class 'ab' was successfully added to it's first child, but if I movesover on other div(other abc) I will get error because first child for that div is not p tag, it's text(abc) and toy cannot apply classlist.add to text.

var hoverTrendingBoxContainer = document.querySelectorAll(".a");
for (i = 0; i < hoverTrendingBoxContainer.length; i++) {
    hoverTrendingBoxContainer[i].addEventListener("mouseover", function () {
        this.firstChild.classList.add("ab");
    });
}
.a{
color:red;
}
.ab{
color:blue;
}
<div class='a'><p class="abc">bc</p></div>
<div class='a'>abc<p>bc</p></div>
<div class='a'>abc<p>bc</p></div>
yajiv
  • 2,901
  • 2
  • 15
  • 25
  • Thanks, the child element was a div so I used firstElementChild instead and it worked. I'll make sure I add all relevant code next time ;) – user9473275 Mar 11 '18 at 19:55