Javascript click button function under certain div - javascript

This is the code of a button in one html page
<a class="btn" role="button" href="#">Click me</a>
I have this javascript code to click a button with a certain class
var clickBtn = document.getElementsByClassName('btn');
for(var i=0;i<clickBtn.length;i++)
{
clickBtn[i].click();
}
This code clicks every button with the class "btn" in ALL the page.
But there are some other buttons in the same page with the same class.
So i want my javascript code to be modifided to click
only a certain button in a certain div.
The code with the div is
<div class="inside">
<span>
<a class="btn" role="button" href="#">Click me</a>
</span>
</div>
Any idea of how can i modify my javascript code to click only the button inside that div??
Thanks for your time.

You can use querySelectorAll()
Array.from(document.querySelectorAll('.inside .btn')).forEach(btn => {
alert(btn.innerHTML)
btn.click();
});
Or without es6:
[].slice.call(document.querySelectorAll('.inside .btn')).forEach(function(btn) {
alert(btn.innerHTML)
btn.click();
});
DEMO
Updated for your comment (Can you update your code that if there is an id in the span like not to click the button?):
[].slice.call(document.querySelectorAll('.inside .btn')).forEach(function(btn) {
if (btn.parentNode.id != 'clicked') {
alert(btn.innerHTML);
btn.click();
}
});
or you can use querySelectorAll() with a :not condition to avoid the if check:
Array.from(document.querySelectorAll('.inside span:not([id="clicked"]) .btn'))
.forEach(btn => {
alert(btn.innerHTML)
btn.click();
});

If you want a non-jQuery solution, you can use getElementById to get the div, and then getElementsByClassName to get all the buttons within that div.
var insideDiv = document.getElementById("inside");
var buttonsInsideDiv = insideDiv.getElementsByClassName();

var parentDiv = clickBtn[i].parentNode;
var clickBtn = document.getElementsByClassName('btn');
for(var i=0;i<clickBtn.length;i++)
{
var parentDiv = clickBtn[i].parentNode;
if(parentDiv == yourDiv)
{
clickBtn[i].click();
}
}
I am not sure, var parentDiv = clickBtn[i].parentNode will work. But the idea is the same.

Related

Toggle class to an element by click another element

I want to click on an element to toggle a class being referenced on a completely unrelated element (not a child, parent or sibling)
For example, initially the code would look like this
<a id="button">Button</a>
<div class="navigation">
Foo
</div>
When the user clicks the element with the id button the HTML would change to look like this (the class "open" is referenced on element with "navigation" already referenced":
<a id="button">Button</a>
<div class="navigation open">
Foo
</div>
The user should be able to toggle the class by clicking the element with the id button.
I would like to use pure javascript to achieve this effect.
You could attach click event to the button with id button then on click select the element with class navigation using getElementsByClassName() (ti will return list of nodes) then select the first one using [0] then use toggle() :
document.getElementById('button').onclick = function(){
document.getElementsByClassName('navigation')[0].classList.toggle("open");
}
Hope this helps.
document.getElementById('button').onclick = function(){
document.getElementsByClassName('navigation')[0].classList.toggle("open");
}
.open{
background-color: green;
color: white;
}
<a id="button">Button</a>
<div class="navigation">
Foo
</div>
You don't really need javascript. Checkboxes work great at storing on/off state. You just need to get a little crafty with the CSS to use it elsewhere. Here is an example:
label.divcheck { color:blue; text-decoration:underline; }
input.divcheck { display:none; }
input.divcheck + div { display:none; }
input.divcheck:checked + div { display:block;}
<label class="divcheck" for="navigation">Button Nav</label>
<label class="divcheck" for="other">Button Other</label>
<input type="checkbox" class="divcheck" id="navigation"/>
<div class="navigation">
Foo
</div>
<input type="checkbox" class="divcheck" id="other"/>
<div class="navigation">
Other
</div>
Multiple elements with class navigation
navigation is a class, so I assume there is more than one element you would like to give class open on click on element with id button. Do it that way:
function toggleNavigation(element) {
element.classList.toggle('open');
}
document.getElementById('button').addEventListener('click', function() {
Array.from(document.getElementsByClassName('navigation')).forEach(toggleNavigation);
});
.navigation {
background-color: lightgreen;
}
.navigation.open {
background-color: lightblue;
}
<a id="button">Button</a>
<div class="navigation">Foo</div>
<div class="navigation">Foo</div>
<div class="navigation">Foo</div>
Single element with class or id navigation
If it is otherwise (i.e., there is only one element with class navigation, in which case it should be an id, not a class) you can replace above JavaScript to:
document.getElementById('button').addEventListener('click', function() {
document.getElementsByClassName('navigation')[0].classList.toggle('open');
});
or if you will change navigation to be an id:
document.getElementById('button').addEventListener('click', function() {
document.getElementById('navigation').classList.toggle('open');
});
You need to add event handlers. This can be done by simple setting the onClick property on the Element object:
document.getElementById('button').onClick = function onClick() {
document.getElementsByClassName('navigation')[0].className += 'open';
};
However, it's preferable that you use addEventListener so multiple event listeners can be added to the same element:
document.getElementById('button').addEventListener('click', function onClick() {
document.getElementsByClassName('navigation')[0].className += 'open';
}, false);
EDIT: It's also better to cache your element references in variables like so:
var button = document.getElementById('button');
var nav = document.getElementsByClassName('navigation')[0];
button.addEventListener('click', function onClick() {
nav.className += 'open';
}, false);
EDIT2: as in Zakaria's answer, you may want to use classList.add(x) instead of className += x. It's more in line with how jQuery's things work. However, be aware that classList is not supported in older versions of IE.
EDIT3: Here's a final version using classList.toggle
var button = document.getElementById('button');
var nav = document.getElementsByClassName('navigation')[0];
button.addEventListener('click', function onClick() {
nav.classList.toggle('open');
}, false);
And here's a quick replacement for classList using className instead:
function classList(elem) {
var cl = {
add: function (clas) {
elem.className += clas;
},
remove: function (clas) {
elem.className = elem.className.replace(clas, '');
},
toggle: function (clas) {
if (elem.className.indexOf(clas) > -1) {
cl.remove(clas);
} else {
cl.add(clas);
}
}
};
return cl;
}
// usage
classList(nav).add('open');
classList(nav).toggle('open');
Try this:
document.querySelector('div.navigation').classList.toggle('open');
This will work if you only have one div element that has the class navigation. It would be better to give it an id, for example id=navigation

jQuery html onclick storing anchor ID, then pulling content from a javascript array

I'm trying to create a html anchor that has a unique ID and then when a user clicks the anchor, the ID gets passed to javascript via the onclick html tag and then a javascript script reads the ID and displays the content in a div. We're using jQuery library for this.
what I have so far:
<a id="MyID1" onclick="var ClickVariable=this.id;return false">1</a>
<a id="MyID2" onclick="var ClickVariable=this.id;return false">2</a>
<script>
var ClickVariable;
var ContentBox = [];
ContentBox[ClickVariable] = "Content for MyID1";
$(ClickVariable).click(function() {
$('.dropdown-menu-content').html(ContentBox);
});
</script>
The above does not work however we have an alternative that works but is not efficient.
<a id="MyID1">1</a>
<a id="MyID2">2</a>
$('#MyID1').click(function() {
$('.dropdown-menu-content').html('Text 1');
});
$('#MyID2').click(function() {
$('.dropdown-menu-content').html('Text 2');
});
As you can see the above one would work but is very repetitive for our needs because we have a large list to enter.
Here is a jsfiddle of the working one that is a tedious repetitive task:
http://jsfiddle.net/2z7o5hn3/
You can reuse the same handler like so:
//mapping id to string to display
var data = {
'MyID1': 'Text 1',
'MyID2': 'Text 2'
}
//shared click handler
var displayEl = $('.dropdown-menu-content');
function handler() {
displayEl.html(data[this.id]);
}
//add click handler to each id
$.each(data, function(k,v) {
$('#'+k).click(handler);
});
http://jsfiddle.net/2z7o5hn3/2/
Give all anchor tags a class and access it like this:
HTML:
<a id="ID1" class="clickVariables" href="#">ID1</a>
<a id="ID2" class="clickVariables" href="#">ID2</a>
JS:
$('.clickVariables').on('click', function(e){
e.preventDefault();
$('.dropdown-menu-content').html($(this).attr('id'));
})
do you mean like this? => DEMO
var texts=['Text 1','Text2'];
$('a[id^=MyID]').click(function() {
$('.dropdown-menu-content').html(texts[$(this).text()-1]);
});

Javascript - selecting and .click()

I'm trying to automate a click when visting a website. This is the HTML I'm looking at.
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
when I select the size, say for instance size 8, the class= tag turns to "box active" like so,
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box active">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
How can I go loop through the class and select a desired size? Also, I was just tinkering around and noticed that I had a hard time simulating a click on the add to cart and other buttons. For the add to cart the HTML looks like this,
<div class="add_to_cart">
<div class="add_to_cart_left">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
<img id="add_to_bag_btn_processing" alt="" src="/images/add_to_bag_processing.gif"></img>
</div>
</div>
Is this the correct chunk of HTML I should be looking at for a simulation of a click?
Since it's Christmas and you sounded excited to see jQuery in action I created a fiddle for you. Here is a sample of what you (could) want using jQuery: http://jsfiddle.net/akkJ5/2/
The code for selecting sizes and twiddling active classes is as follows:
var selectedSize = '';
$(".box").click(function(){
$(".box").removeClass('active');
$(this).addClass('active');
selectedSize = $(this).html();
$("#messages").html(selectedSize +" was selected");
});
In it I create an event listener for clicks on all box class elements. Since only one should be active I remove the active class from all box class elements then add active to the clicked box. I save the innerHTML of the selected link as selectedSize, and write it to an element for display sake.
In terms of simulating a click on a button you could do something like this:
$(".add_to_cart").click(function(){
alert('cart clicked');
});
$(".add_to_cart").trigger('click');
Updated
To attach event to all the classed you can do
var selectedvalue = '';
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
d.onclick = function (e) {
selectedvalue = this.text;
this.className = this.className + " active";
}
}
Check http://jsfiddle.net/raunakkathuria/Nv8t2/2/
To navigate through classes and add your class to the link that has same value
JS
var value = 8;
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
if(d.text == value) {
d.className = d.className + " active";
}
}
To simulate the click handler for the add to cart you can enclose them to
<a href="javascript:void(0)" onclick="myJsFunc();">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
</a>
If you want to send it some link update this href="javascript:void(0)" onclick="myJsFunc();" to href="your_link"
Check http://jsfiddle.net/raunakkathuria/Nv8t2/1/

Analysing button in html to check if can register for events

I want to register for events on a button in a web page using javascript addEventListener or something equivalent. But the web page doesn't appear to have standard form buttons. The html snippet below is the html markup for what appears as a button on the page.
I want to detect mousedown (or mouseclick or equiv). Is there any way I could detect the user clicking on this button?
<a href="javascript:" id="WIN_0_536870914" arid=536870914 artype="Control" ardbn="Dial" artcolor="null" class="btn btn3d arfid536870914 ardbnDial" style="top:247; left:115; width:46; height:21;z-index:1001;">
<div class="btntextdiv" style="top:0; left:0; width:46; height:21;">
<div class="f1" style=";width:46">Dial</div>
</div>
</a>
The only tricky bit will be getting the elements from the DOM in the first place. If you know the id then it's trivial to get this specific button:
var elem = document.getElementById('WIN_0_536870914');
elem.addEventListener('click', function () {
alert('click!');
});
http://jsfiddle.net/ugsYB/
Although you probably want to target all the buttons by their class:
var elems = document.getElementsByClassName('btn');
var i;
for(i = 0; i < elems.length; i++) {
var elem = elems[i];
elem.addEventListener('click', function () {
alert('click!');
});
}
http://jsfiddle.net/ugsYB/1/ (Note: there are cross browser issues with getElementByClassName)
Of course, jQuery makes this sort of thing trivial:
$('.btn').click(function () { alert('click!'); });
http://jsfiddle.net/ugsYB/2/
But it might be overkill for your needs.

Jquery detecting clicked element id

I'm trying to use the same function to slide up and down a text area. using jquery's slidetoggle.
How can I make javascript detect the clicked element in order to know which box to expand.
Here is what I have
function slidedown(id){
$(id+'text').slideToggle(500);
}
that is my function
in my html I have this
<a id="reroof" href="javascript:slidedown(this)">reroof</a>
the section i want to expand is called rerooftext
however when I check the value of id.id I says undefined.
Any ideas?
try the following code:
html code:
<a id="reroof" href="#" onclick="javascript:slidedown(this)">reroof</a>
JS code:
function slidedown(val){
var id = val.id;
alert(id);
$(id+'text').slideToggle(500);
}
In html you are passing the element(this refers the element not an id)
Working Example:
http://jsfiddle.net/jAkMq/
In your HTML:
<a id="reroof" href="#">reroof</a>
In your javascript:
$("#reroof").click(function (e) {
var id = "#" + this.id + "text";
$(id).slideToggle(500);
e.preventDefault();
});
try this
<a id="reroof" href="javascript:void(0)" onclick="slidedown(this)">reroof</a>
function slidedown(obj){
$(obj.id+'text').slideToggle(500);
}
javascript:slidedown(this). here this will be the element not the id

Categories