Search code examples
javascripthtmldomgetelementsbytagnamegetelementsbyclassname

Javascript - targeting p tags within a div not returning anything


I have two divs with class of "thing". I want to access all the p tags within them using them using javascript and change their color. This is what I'm trying but it's not working:

<div id="top" class="thing">
    <p>kdjflksj siuiotue</p>
    <p>kdjflksj siuiotue</p>
    <p>kdjflksj siuiotue</p>    

</div>

Javascript

   var changes = document.getElementsByClassName("thing");
   var pchanges = changes.getElementsByTagName("p");

   for(let i = 0; i < pchanges.length; i++) {

    pchanges[i].onmouseover = function() {

        this.style.color = "blue";
    }

    pchanges[i].onmouseout = function(){
        this.style.color = "black";
    }

}

The javascript is within a window.onload function.


Solution

  • Your variable changes is an HTMLCollection which doesn't have a getElementsByTagName method. You would have to call that method on each element inside the collection to get what you want. However, this looks like a good place to use document.querySelectorAll instead, so that you can get the elements you want in a single call:

    var pchanges = document.querySelectorAll(".thing p");
    
    for(let i = 0; i < pchanges.length; i++) {
        pchanges[i].onmouseover = function() {
            this.style.color = "blue";
        }
    
        pchanges[i].onmouseout = function(){
            this.style.color = "black";
        }
    }
    <div id="top" class="thing">
        <p>kdjflksj siuiotue</p>
        <p>kdjflksj siuiotue</p>
        <p>kdjflksj siuiotue</p>    
    </div>