Simple html button that I want to alert when clicked.
HTML:
<div id="container>
<button type="button>Click Me</button>
</div>
Javascript:
var cat = document.getElementById("container");
var dog = cat.getElementsByTagName("button");
function mouse (){
alert("mouse")
};
dog.addEventListener("click", mouse, false);
If I target the container with:
cat.addEventListener("click", mouse, false);
Works fine anytime I click on the div, but when I try to add it to the button, nothing happens. I have also tried...
dog.addEventListener("click, mouse(), false);
When I try that code, the mouse function runs on load.
Simple html button that I want to alert when clicked.
HTML:
<div id="container>
<button type="button>Click Me</button>
</div>
Javascript:
var cat = document.getElementById("container");
var dog = cat.getElementsByTagName("button");
function mouse (){
alert("mouse")
};
dog.addEventListener("click", mouse, false);
If I target the container with:
cat.addEventListener("click", mouse, false);
Works fine anytime I click on the div, but when I try to add it to the button, nothing happens. I have also tried...
dog.addEventListener("click, mouse(), false);
When I try that code, the mouse function runs on load.
Share Improve this question edited Jul 29, 2014 at 16:21 Brian asked Jul 29, 2014 at 16:14 BrianBrian 3153 gold badges7 silver badges12 bronze badges 1-
2
getElementsByTagName
returns an array of node list. There are actually multiple errors there with missing quotes in HTML, button close tag having a typo etc. – Harry Commented Jul 29, 2014 at 16:17
2 Answers
Reset to default 4Your JS is wrong:
Instead of GetElementById
should be getElementById
. Javascript is case sensitive.
And I don't see where do you have hide
function declaration. I see only mouse
function that is never used.
Also according to @Harry ment by calling getElementsByTagName
you will get DOM elements collection. So you should use:
dog[ 0 ].addEventListener("click", hide, false);
lots of misspellings
//get not Get
var cat = document.getElementById("container");
//get first of array
var dog = cat.getElementsByTagName("button")[0];
function mouse (){
alert("mouse")
};
//no hide function
dog.addEventListener("click", mouse, false);