0

I've been trying to learn something about JavaScript today, came across events and somehow I'm stuck at it.

When I call the first function it just works, however if I call the second one it doesn't execute the function for some reason? I've tried doing it without the windows.onload event I've tried putting the script code inside head element or just above the closing body tag but nothing has changed, any tips?

function peh() {
    
    document.onclick = function(){
    alert("you clicked");
}
}

function second(){
    var myElement = getElementsByTagName("mImg");
    myElement.onclick = function(){
        alert("clicked img");
    }
}

window.onload = function() {
    second();
}

3 Answers 3

1

I guess you have to change your code like that :

function second(){
   var myElement = document.getElementsByTagName("mImg");
   myElement[0].onclick = function(){
    alert("clicked first img");
   }
}

Because getElementsByTagName selector is returning array. And you can make it "for" or "while" loop for each element.

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

Comments

0

You use getElementsByTagName which receives the DOM HTML tag name, say, 'td' Better use getElementsById, as I guess mImg is an ID of some element...

1 Comment

yeah, i didn't change that when i copied it here, but it doesn't work with getElementById either
0

Thanks to jquery framework you will not bother yourself about those things anymore . just use jquery functions .

$(document).ready(function(){
$(mImg).click(function(){
   alert("goood");
 });
});

or for dynamic tags :

$(document).on("click","mImg",function(){
alert("goood");
});

1 Comment

Yeah, I know where you are getting :) The thing is I want to have some basic knowledge and understanding of pure javascript before moving on to jQuery and other frameworks

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.