var btn = document.querySelectorAll('.button');
function test() {
alert('hello')
}
btn.addEventListener("click", test);
After clicking on the "button" - test function should be called, bit it's not.
'.button' will search for all elements with class named 'button'. If you are searching for button elements you should write: document.querySelectorAll('button')
Additionally querySelectorAll gives nodeList.
For this code:
<button id="myBtn">Try it</button>
<button id="myBtn2">Try it</button>
<script>
var btn = document.querySelectorAll('button');
console.log(btn);
</script>
return will be NodeList[button#myBtn, button#myBtn2], as you can see it is an array.
document.querySelectorAll would return the list of elements. You need
to apply the click event on individual elements.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
var btn = document.querySelectorAll('.button');
console.log(btn[0]);
function test() {
alert('hello')
}
btn[0].addEventListener("click", test);
<div class = 'button'>Button</div>
Related
I'm trying to set up a listener for a button that does not have an ID. How would I create a listener for the following element:
<button class="jss459 jss433 jss444 jss445 jss447 jss448 jss321" tabindex="0" type="button" title="Press Enter"><span class="jss434">Quick Search</span><span class="jss471"></span></button>
const myelement = document.querySelector('.jss459.jss433.jss444.jss445.jss447.jss448.jss321');
or
const myelement = document.querySelector('[title="Press Enter"]');
But you'd probably be better off with a more unique selector :)
querySelector()
It allows You to grab the element by the class name
const button = document.querySelector(<classHere>);
button.addEventListener('click', ()=> {
//code here
})
You can use document.querySelector to return the first element that matches the selector, for example:
document.querySelector('button').addEventListener('click', event => {
console.log('The button was clicked');
});
<button class="jss459 jss433 jss444 jss445 jss447 jss448 jss321" tabindex="0" type="button" title="Press Enter"><span class="jss434"> Quick Search</span><span class="jss471"></span> </button>
It sounds to me that you ONLY want to select a button that doesn't have an ID attribute. In that case, you can use querySelectorAll to select all the buttons on the page and then add an Event Listener the buttons that don't have the ID attribute. Below would be the code for that:
let allButtons = document.querySelectorAll('button')
allButtons.forEach( button => {
if (!button.hasAttribute('id')) {
button.addEventListener('click', buttonWithoutId)
}
})
function buttonWithoutId() {
alert('this button does not have an ID!')
}
I'm learning JavaScript and I'm trying to add an event listener to my button.
Here is my HTML (Yes, the script is loaded after the button):
<html>
<body>
<button>Click me</button>
<body>
<script src="experimenting2.js"></script>
</html>
And Here's my JS code:
alert("Connected");
var body = document.getElementByTagName("body");
var button = document.getElementByTagName("button");
button.addEventListener("click", function() {
alert("Clicked");
body.style.background = "pink";
});
The first alert at the beginning of the JS file gets triggered when I load up the page but the second one inside the addEventListener doesn't get triggered.
There is nothing like document.getElementByTagName("body"); It is document.getElementsByTagName("body"); which returns you the collection and you need to loop through this collection to attach events to each node in it
Or you can use document.querySelector('body') to select the body and document.querySelector('button') to select the button
Read here about document.querySelector
alert("Connected");
var body = document.querySelector("body");
var button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Clicked");
body.style.background = "pink";
});
<html>
<body>
<button>Click me</button>
<body>
</html>
The method signature to get elements by tag name is
getElementsByTagName(..)
But you are using
getElementByTagName(..)
Any way in the following code
var button = document.getElementsByTagName("button");
You are getting a collection of buttons and not a single button. Where do you want to add the EventListener?
A better way can be to access the element by Id by assigning id to the button in HTML
var button = document.getElementById("someid");
Otherwise, you can also try as you have only single button which you are intending to add EventListener to
var button = document.querySelector("button");
getElementByTagName should be getElementsByTagName
And you can use querySelector instead of getElementsByTagName like this:
var button = document.querySelector("button");
And you don't have to assign a variable for the body. Just reference it with document.body like this:
document.body.style.background = "pink";
So your complete code should look like this:
alert("Connected");
var button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Clicked");
document.body.style.background = "pink";
});
<button>Click me</button>
jsFiddle: https://jsfiddle.net/AndrewL64/2cscc5ka/
actually the problem is that you are calling getElementByTagName and it is getElementsByTagName. also it returns an array of items.
check the working sample:
console.log("Connected");
var body = document.getElementsByTagName("body")[0];
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function() {
console.log("Clicked");
body.style.background = "pink";
});
<html>
<body>
<button>Click me</button>
<body>
<script src="experimenting2.js"></script>
</html>
Also check that it will be easier using the id property and the function getElementById
console.log("Connected");
var body = document.getElementById("body");
var button = document.getElementById("button");
button.addEventListener("click", function() {
console.log("Clicked");
body.style.background = "pink";
});
<html>
<body id="body">
<button id="button">Click me</button>
<body>
<script src="experimenting2.js"></script>
</html>
I want to attach the "click" event to all button inside a div. Except this:
var div1 = document.getElementById("div1");
var elements = div1.getElementsByTagName('button');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
// stuff
}
}
Is there a better way to attach "onclick" function handler to all the buttons at once in pure js?
As mentioned in the comments, you can use event delegation. In that case, a single event handler is added to a common ancestor of the elements you want to handle. Inside the handler, the element where the event originated is inspected and if it is one of the ones that should be handled, the actual event handler logic is executed.
In your case it could be like:
var div1 = document.getElementById('div1');
div1.onclick = function(event) {
if (event.target.nodeName.toLowerCase() !== 'button') {
return;
}
// stuff
};
Note that there differences in the event system between browsers, especially older IE versions. You will have to deal with that if want to support those versions. You might also want to consider using addEventListener instead of onclick.
In order to reduce the code you can define a clickHandler function and attach this function to all buttons.
The result of div1.getElementsByTagName('button') is an HTMLCollection and not an array. In order to take advantage of Array.forEach syntax you can use call.
The example:
var clickHandler = function (e) {
console.log(this.textContent);
};
var div1 = document.getElementById("div1");
var elements = div1.getElementsByTagName('button');
Array.prototype.forEach.call(elements, function(ele) {
ele.onclick = clickHandler
});
<div id="div1">
<button type="button">Button 1</button>
<button type="button">Button 2</button>
<button type="button">Button 3</button>
<button type="button">Button 4</button>
</div>
If you can use the Arrow Functions, they are supported only in ES6, you can compact more your code:
var clickHandler = function (e) {
console.log(this.textContent);
};
var div1 = document.getElementById("div1");
var elements = div1.getElementsByTagName('button');
Array.prototype.forEach.call(elements, (ele) => {ele.onclick = clickHandler;});
<div id="div1">
<button type="button">Button 1</button>
<button type="button">Button 2</button>
<button type="button">Button 3</button>
<button type="button">Button 4</button>
</div>
This is a example code in JavaScript: The Definitive Guide,6th Edition.
<button id="my button">click me</button>
<script>
var b = document.getElementById("my button");
b.onclick = fuction(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
b.addEventListener ("click", function(){ alert("Thanks again!");}, false);
</script>
When I click the button, nothing happen.
are you sure you write well?
1 - Remove space on id value: change id="my button" to id="mybutton".
2 - is not fuction, is function.
<button id="mybutton">click me</button>
<script>
var b = document.getElementById("mybutton");
b.onclick = function(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
b.addEventListener ("click", function(){ alert("Thanks again!");}, false);
</script>
Your button id can't have a space between the words. Use an underscore instead like <button id="my_button">click me</button>
Also, in your function call for your onclick you spelled function wrong.
See JSFiddle for working example:
https://jsfiddle.net/us2dq8sz/
Wrong spelling in this line
b.onclick = fuction(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
fuction instead of function
Working version : https://jsfiddle.net/x46ugomj/
The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().