getElementByClassName onclick issue - javascript

I would like to know how can I detect that the button is clicked using getElementByClassName. The button doesn't have an ID and is generated as a part of embedded iframe.
<button class="playButton medium" role="application" title="Play" style="color: rgb(204)</button>
I am trying this script that would alert if the button is clicked, but it doesn't seem to work for me.
var x = document.getElementByClassName("playButton medium");
for (var i=0; i < x.length; i++) {
x[i].onclick = function() {
alert("clicked");
}
};
Thank you for any advice

Firstly it's getElementsByClassName(), note the plural s. Secondly, you can only supply a single class as an argument to that function. Also it's better practice to use addEventListener() over on* event properties. Try this:
var x = document.getElementsByClassName("playButton");
for (var i = 0; i < x.length; i++) {
x[i].addEventListener('click', function() {
console.log("clicked");
});
};
<button class="playButton medium" role="application" title="Play" style="color: rgb(204)">Play</button>
If you wanted to select the elements using both classes you could instead use document.querySelectorAll('.playButton.medium').

Related

How would I get an alert to appear when I click on an a button in a class?

I have several buttons in my webpage in the 'addbutton' class and I want an alert to pop up any time any one of them is clicked. How would you do this?
Here are some JS pieces of code I have already tried (that have not worked):
addbuttons = document.getElementsByClassName("addbutton")
addbuttons.onclick {
for (var i=0; i<addbuttons.length; i++) {
alert("hi")
}
document.getElementsByClassName("addbutton").onclick = function() {
alert("hi")}
And my HTML:
<input type="checkbox">
<p>Breakfast:</p>
<button class="addbutton">+</button>
<div></div>
<br>
<input type="checkbox">
<p>Mid-Morning:</p>
<button class="addbutton">+</button>
<div></div>
<br>
document.getElementsByClassName("addbutton") returns an Array(HTMLCollection to be precise).
Also, you need to set the onclick to a function, you cannot use the syntax .onclick { }.
To set a listener for every button you will need to use a for loop somewhat like this
for(let i = 0; i < addbuttons.length; i++){
addbuttons[i].onclick = function(){
alert('Works!')
}
}
Or if you are using ES6
for(let addButton of addbuttons){
addButton.onclick = function(){
alert('Works!')
}
}
Probably relevant links,
https://www.w3schools.com/js/js_loop_for.asp
https://www.w3schools.com/jsref/event_onclick.asp
Let's define your event:
function myEvent() {
alert("hi");
}
Now let's get your elements by class name, loop them and add an event listener to them:
for (let btn of document.getElementsByClassName("addbutton")) btn.addEventListener("click", myEvent);
Your mistake was that you assumed that you have an onclick for the set of elements, returned by getElementsByClassName, however, you only have onclick for the elements inside the set.

Binding an event listener to multiple elements with the same class

I'm trying to apply the onclick event with JavaScript to the following elements:
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
If I click on the first element (with index [0]) then this works, but I
need this event applicable for all classes:
document.getElementsByClassName('abc')[0].onclick="function(){fun1();}";
function fun1(){
document.getElementsByClassName('abc').style.color="red";
}
.onclick does not expect to receive a string, and in fact you don't need an extra function at all.
However, to assign it to each element, use a loop, like I'm sure you must have learned about in a beginner tutorial.
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
this.style.color = "red";
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
To expand on the solution provided by #rock star I added two small additions to the function. First it is better to add / reemove a class (with an associated style rule) to an element than directly applying the stylerule to the element.
Secondly - on the click event - this will now remove the red class (and therefore style) from the previously selected element and add it to the new element. This will allow only one element to be red at a time (in the original solution any element that was clicked would become red).
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
var oldLink = document.getElementsByClassName('red')[0];
if(oldLink) {oldLink.classList.remove('red')};
this.classList.add('red');
}
.red {
color:red;
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
This works:
<body>
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
<script>
var elements = document.getElementsByClassName('abc');
for(var i = 0, max = elements.length; i < max; i += 1) {
var clickedElement = elements[i];
clickedElement.onclick=function (){
fun1(this);
};
}
function fun1(element){
element.style.color="red";
}
</script>
</body>

Different ways to click a hyper link programmatically?

What are some other ways to programmatically click a text link on a page? The link does not have a ID and will not have one.
example link will look like this:
<div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">
Click Here
</div>
Here's one way I can do it but want to know more ways to click it.
var els = document.getElementsByTagName('a');
for (var i = 0, l = els.length; i < l; i++)
{
var el = els[i];
if (el.text === 'Click Here')
{
el.click()
}
}
It can't have an id? That would be the best route IMO. Second best approaches:
Assign a class, and look up by class
or
Assign an id or class to the parent object, and look up the first "a" child

Click All Buttons on Page

I was wondering if anyone could help with a simple JavaScript code to click all buttons with the same value name/input name on a page?
They each share:
<input name="all" type="submit" value="Do All">
Here's a screenshot of the buttons: http://oi61.tinypic.com/2nqblnr.jpg
Maybe one should make a button that works as a "click all" button? This will be a chrome extension (for personal use), so I can't really go about changing the "do all" button's code.
I was having a hard time finding it on Google, and I'm fine with HTML/CSS but really terrible with JavaScript.
To click all the buttons on the page with the same name you can use getElementsByName() function and set it to a variable which will hold all the buttons in a NodeList then loop through the NodeList and call the click() event for each button.
For example:
// Get all buttons with the name 'all' and store in a NodeList called 'buttons'
var buttons = document.getElementsByName('all');
// Loop through NodeList and call the click() function on each button
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
// Select all buttons with class .btn
const inputBtns = document.querySelectorAll('[name="all"]');
// Select click all button
const clickAllBtn = document.querySelector('.click-all');
// Attach click handler to all input buttons
for(let i = 0; i < inputBtns.length; i++) {
inputBtns[i].addEventListener('click', function() {
alert(this.value);
})
}
// Click all buttons, when user click .click-all button
clickAllBtn.addEventListener('click', function() {
for(let i = 0; i < inputBtns.length; i++) {
inputBtns[i].click();
}
})
<input name="all" type="submit" value="Do All 1">
<input name="all" type="submit" value="Do All 2">
<button type="button" class="click-all">
click all
</button>
This worked for me assuming the of those elements had href="#show" or something similar
var buttons = document.querySelectorAll('[href="#show"]');
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
I guess this is what you want to achieve :
jsfiddle : http://jsfiddle.net/vqk2V/
Achieved using .click()[http://api.jquery.com/click/] method of jquery.
With Java...maybe using Selenium. But you can use jquery (javascrpt's framework) so the code could be:
<scrpipt>
function ClickAllButtons()
{
if($("input[type=button][name='someName']").length > 0)
{
$('input[type=button]').each(function(i){
var $currentButton = $(this);
$currentButton.click();
});
}
}
</script>
var buttons = document.getElementsByClassName('uArJ5e');
// Loop through NodeList and call the click() function on each button
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
This will click all buttons on google ;)
What you would want to do is create a class eg.
public class MyClass{
........
}
..and then create methods which do the processing that is done when you click your buttons.
Then call the methods with an object if your methods are non static in the specific buttons you require the method in.
Now you can create a button which calls all the methods you want to call and it will do what you are asking for.

JS call code block upon clicking one of many items with specific class

I have a page with a bunch of buttons that all have a class (actually two classes, each separated by a space; I can use either or both). I need to call a function or a block of code (let's say an alert for this example) when the user clicks one of these buttons with this class. I do not have access to the HTML so the link itself can't call the function. I don't need to know which button. How do I do this with pure JavaScript (no jQuery)?
you can do something like this:
var btns = document.getElementsByClassName('test');
for (var i = 0; i < btns.length; i++){
btns[i].onclick = function(){
alert(this.innerHTML)
}
}
demo
Just loop through each one by class and bind the event handler.
var elems = document.getElementsByClassName('cls');
for(var i = 0; i < elems.length; i++) {
elems[i].onclick = function() {
alert('Clicked');
};
}

Categories

Resources