Search code examples
javascripthtmlgetelementsbytagname

Script only changes first <p> element


Below is the javascript I have for my page:

    window.onmouseover = function(){
        var body = document.getElementsByTagName("body")
        var h1 = document.getElementsByTagName("h1");
        var a = document.getElementsByTagName("a");
        var p = document.getElementsByTagName("p")
        for(var j = 0; j < p.length; j++) {
            body[j].style.fontFamily = "helvetica";
            body[j].style.backgroundColor = "rgb(250, 250, 240)"
            p[j].style.fontFamily = "courier";
            a[j].onclick = function() {
                this.style.backgroundColor = "Black"
            }
        }
    }

I have one h1 element, one a element, and 10 p elements. For some reason, this code only changes the font of the first p element, although everything else works fine? Why is this and how can I fix it?


Solution

  • If you have only one a element and (of course) only one body you cannot iterate over 10 of them. This causes an error on the second iteration of the cycle. Use this code instead.

    window.onmouseover = function(){
        var body = document.getElementsByTagName("body")
        var h1 = document.getElementsByTagName("h1");
        var a = document.getElementsByTagName("a");
        var p = document.getElementsByTagName("p")
    
        body[0].style.fontFamily = "helvetica";
        body[0].style.backgroundColor = "rgb(250, 250, 240)"
        a[0].onclick = function() {
            this.style.backgroundColor = "Black"
        }
    
        for (var j = 0; j < p.length; j++) {
            p[j].style.fontFamily = "courier";
        }
    }