Click object by classname - javascript

I am trying document.getElementsByClassName('classname').click();, but it doesn't fire the click on the class. Why is that?

Why is that?
Because the getElementsByClassName method returns an array of DOM elements. And calling a click method on an array hardly makes sense. If you want to call this click method you could do that on some particular element of the array. For example if you wanted to call it on the first element (assuming the array is not empty of course):
document.getElementsByClassName('classname')[0].click();
But since you have tagged your question with jQuery you probably just wanted to write:
$('.classname').click();

document.getElementsByClassName('classname') returns an array of DOM nodes.
Try:
var nodes = document.getElementsByClassName('classname');
for(var i = 0; i < nodes.length; i++) {
nodes[i].click();
}
Also remember that getElementsByClassName is not supported by every browser.

try this:
$(function() {
$('.classname').click();
});

Your code will work with
document.getElementsByClassName('classname')[0].click();
But, if you use jquery then
$(document).ready( function(){
$('.classname').on('click',function(event){});
});
OR simply $('.classname').click();

Because that will return a set of elements, which is usually an HTMLCollection. You have to then iterate through it:
https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByClassName
Pure Javascript:
var elements = document.getElementsByClassName('xxx');
for(var i = 0; i < elements.length; i++)
{
elements[i].addEventListener('click',function(){window.alert('Class name is xxx');},false);
}
JQuery:
$(document).ready(function(){
$('.xxx').on('click',function(){window.alert('Class name is xxx');});
});

Related

Using querySelectorAll inside a for-in-loop

I'm feeling a little stupid to ask this because it should be so simple, but I'm getting pretty frustrated.
I have a few divs that I want to show only one at a time, so I want to hide the rest. My approach:
var elements = document.querySelectorAll("div");
for (i in elements) {
elements[i].style.setProperty("display", "none");
}
Firefox always says elements[i].style.setProperty(); is undefined.
I've made a workaround using a normal for-loop without using in, but I'd still like to know why this doesn't work.
Thanks in advance!
Replace
elements[i].style.setProperty("display", "none");
with
elements[i].style.display = "none";
As the HTMLElement.style property returns a CSSStyleDeclaration object that represents the element's inline styles as properties, i.e. style.property = 'value'
And use a regular for loop when iterating over array-like objects that has a length, like nodeLists
var elements = document.querySelectorAll("div");
for ( var i=0; i<elements.length; i++) {
elements[i].style.display = "none";
}

Why can't I make "onclick" event handler in my javascript code? [duplicate]

I am using getElementById when I need to clone the div element.
Code:
printHTML( document.getElementById("div_name").cloneNode(true));
Now I need to use getElementsByClassName
CloneNode is not working when using getElementsByClassName.
How can I put class name in here?
Thank's
EDIT:
When I try to use this:
printHTML( $('.dataTables_scroll').clone(true) );
You can see my function:
function printHTML(clonedDive){
var iframe = document.createElement("iframe");
document.body.appendChild(iframe);
iframe.contentWindow.onunload = function(){
$(".DTTT_container").show("fast");
$("#header_outer").show("fast");
$(".ColVis.TableTools").show("fast");
$("#footer").show("fast");
};
iframe.contentWindow.document.body.appendChild(clonedDive);
iframe.contentWindow.print();
document.body.removeChild(iframe);
}
I am getting an error in this line:
iframe.contentWindow.document.body.appendChild(clonedDive);
This is an error description:
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
getElementsByClassName gets a nodelist, or an array-like object containing elements if you will, as there can be more than one element with the same class.
getElementsByClassName does this even if only one element matches the class.
You can generally recognize methods like that be the s in getElements, which means it gets multiple elements, i.e. a nodeList.
getElementById only gets one element as ID's are unique.
To get the first element in the nodelist, use bracket notation, like so:
document.getElementsByClassName("div_name")[0].cloneNode(true);
or one could use querySelector, which gets the first matching element only
document.querySelector(".div_name").cloneNode(true);
The jQuery solution would be:
$('.div_name').clone(true);
and to iterate over elements with a certain classname you'd use a loop
var elems = document.getElementsByClassName("div_name");
for ( var i=0; i<elems.length; i++ ) {
printHTML( elems[i].cloneNode(true) );
}
Due to getElementsByClassName returns an object's array, so you have to use for loop to iterates among them, as follows:
for (i = 0; i < document.getElementsByClassName("div_name").length; i++){
printHTML( document.getElementsByClassName("div_name")[i].cloneNode(true));
}
otherwise, if you know the index of the element you have let we say 1
printHTML( document.getElementsByClassName("div_name")[1].cloneNode(true));
This does not work? :
printHTML( document.getElementsByClassName("class_name")[0].cloneNode(true));
You can loop through the elements and clone one by one...
var e = document.getElementsByClassName('div');
for (var i = 0; i < e.length; i += 1) {
// Clone e[i] here
console.log(e[i].cloneNode(true));
}

Can't set styles to elements with a specified class javascript

This is my javascript code:
document.getElementsByClassName('loader').style.opacity = "0";
this code will give an error in my console displayed below:
TypeError: 'undefined' is not an object (evaluating 'document.getElementsByClassName('loader').style.opacity = "0"')
I have already tried these, but these also do not work:
document.document.querySelectorAll('.loader').style.opacity = '0';
document.document.querySelector('.loader').style.opacity = '0';
My html code:
<div class="loader">Some Text</div>
The .getElementsByClassName() function returns a list of elements. You have to iterate over that list with your own code.
var loaders = document.getElementsByClassName('loader');
for (var i = 0; i < loaders.length; ++i)
loaders[i].style.opacity = '0';
If you just want to operate on particular members of the list, you can (if you're careful) treat it like an array. I mention being careful because .getElementsByClassName() returns a "live" NodeList. If you remove the class "loader" from one or more of the elements, the list will change. (That's not the case for the lists returned from .querySelectorAll().)
If you select elements by classes you most will most likely end up with an array of elements. You need to set the parameters for each one. Pure JS doesn't behave as jQuery regarding this.
First make your selection by
var elements = document.getElementsByClassName('loader');
then cycle through them
for(var i=0; i<elements.length; i++){
elements[i].style.opacity = "0";
}
See if this helps..

jQuery equivalent for attaching a handler

What is the equivalent code in jQuery for the below JavaScript function?
function attachSomeHandler(in) {
for(var i = 0; i < in.length; i++) {
if(in[i].type == 'submit')
in[i].attachEvent("onclick", someFunc);
}
}
Assuming the argument in is an array of DOM elements and you already have that array and you want to reproduce the exact same function attachSomeHandler(), you could do this using jQuery:
function attachSomeHandler(in) {
$(in).filter('[type="submit"]').click(someFunc);
}
If you want to back up to a higher level in your code, you can create a single jQuery selector that would get the original array of DOM elements that was already filtered to only have ones with the appropriate type.

jquery name selector not working in ie6

var brands = document.getElementsByName("brand");
for(var brand in brands){
$("input[name='brand']").eq(brand).click(function(){
alert("hello22");
loadDataFN(1);
});
}
This code is not executing in ie6,
Any help would be appreciated.
The problem is likely that you are trying to use a for-in construct to iterate over a numeric array. This often won't give expected results. Use an incremental for loop instead:
var brands = document.getElementsByName("brand");
// Use an incremental for loop to iterate an array
for(var i=0; i<brands.length; i++){
$("input[name='brand']").eq(brands[i]).click(function(){
alert("hello22");
loadDataFN(1);
});
}
However,
after seeing the first part of your code, the loop appears unnecessary. You should only need the following, since you are assigning the same function to all brand inputs.
// These will return the same list of elements (as long as you don't have non-input elements named brand)
// though the jQuery version will return them as jQuery objects
// rather than plain DOM nodes
var brands = document.getElementsByName("brand");
$("input[name='brand']");
Therefore, the getElementsByName() and loop are not necessary.
$("input[name='brand']").click(function() {
alert("hello22");
loadDataFN(1);
});
for-in loops are used for iterating over the properties of an object, not over the elements of an array.
Why don't you write the code without jQuery if this doesn't work?
Something like this:
function getInputByName(name) {
var i, j = document.getElementsByTagName('input').length;
for(i=0;i<j;++i) { // You can also use getAttribute, but maybe it won't work in IE6
if(document.getElementsByTagName('input')[i].name === name) {
return document.getElementsByTagName('input')[i];
}
}
return null;
}
I don't know jQuery, but maybe you can do something like this:
$(getInputByName('brand')).eq(brand).click(function(){
alert("hello22");
loadDataFN(1);
});

Categories