0

I have created 2 functions in javascript, these functions are fired on click events, the problem is that after the for loops, alerts are not executed.

function myfunc() {
    for (var i = 0; i < 4; i++) {
        document.getElementsByTagName("h1")[i].style.color="red";
    }

    alert("alert 1"); //this should be executed after the for since it is part of the function code.
}

function myfunc2() {
    for (var j = 0; j < 4; j++) {
        document.getElementsByTagName("h1")[j].style.color="navy";		
    }

    alert("alert 2"); //this should be executed after the for since it is part of the function code
}
<h1 onClick="myfunc()">primo h1</h1>
<h1 onClick="myfunc2();">secondo h1</h1>

3
  • Are the bodies of the loop executed? the attribute is usually written onclick (without a capital letter), I don't know if the case is important. Commented May 21, 2016 at 0:30
  • Are there at least four <h1>s for each function? Commented May 21, 2016 at 0:32
  • Changing the length as @MaxStarkenburg suggested, works fine. Get the length using something like: var h1Len = document.getElementsByTagName("h1").length; and use insted of the hardcoded number Commented May 21, 2016 at 0:34

1 Answer 1

1

You need to check how many h1 tags there are in the DOM before applying new style attributes. You are effectively trying to make changes to undefined.

var elements = document.getElementsByTagName("h1");

function myfunc() {
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.color="red";
    }

    alert("alert 1"); //this should be executed after the for since it is part of the function code.
}

function myfunc2() {
    for (var j = 0; j < elements.length; j++) {
        elements[j].style.color="navy";
    }

    alert("alert 2"); //this should be executed after the for since it is part of the function code
}
<h1 onClick="myfunc()">primo h1</h1>
<h1 onClick="myfunc2();">secondo h1</h1>

Sign up to request clarification or add additional context in comments.

2 Comments

why would you store the DOM node on a elements var and call from the DOM once again inside the for-loop instead of using your elements
It was a quick copy from the original question. Corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.