how do i select all divs with javascript [duplicate] - javascript

This question already has answers here:
JavaScript and getElementById for multiple elements with the same ID
(13 answers)
Closed 4 years ago.
i am trying to create a filter with a checkbox when someone clicks on the check box it will hide all the div1
//so far i have used
function div1hide() {
document.getElementById("dive1").style.display ='none';
}
var hider = document.getElementById("div1");
document.addEventListener("click", dive1hide, false);
< id="div1">test</div>
< id="div1">test</div>
< id="div1">test</div>
< id="div1">test</div>
it only hides the first one i m not sure why its not hiding all the other ones...

Something like this maybe?
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<input type="checkbox" id="hider" />
<script>
var div1 = document.getElementsByClassName("div1"); // divs to control
var hider = document.getElementById("hider"); // checkbox
div1.toggleStatus = "on"; // let's go!
hider.onclick = function(){ // what happen when hitting the checkbox
switch(div1.toggleStatus){ // two options
case "on": // 1: hide it!
div1.toggleStatus="off"; // hit the checkbox again and jump to 2nd option
for (i = 0; i < div1.length; i++) { // choose all elements
div1[i].style.display = "none"; // hide them
}
break;
case "off": // 1. show it!
div1.toggleStatus="on"; // hit the checkbox again and jump to 1st option
for (i = 0; i < div1.length; i++) { // choose all elements
div1[i].style.display = "block"; // show them
}
break;
}
}
</script>

Change this to look more like this. getElementsByClassName returns an object, which can then be iterated through to change the display of all the elements in that selection.
function div1hide() {
var els = document.getElementsByClassName("div1");
for(const el in els){
els[el].style.display = "none";
}
}
var hider = document.getElementsByClassName("div1");
document.addEventListener("click", div1hide, false);
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>

function div1hide() {
var els = document.getElementsByClassName('div1');
for(var i = 0; i < els.length; i++){
els[i].style.display = 'none';
}
}
document.getElementById('hide').addEventListener('click', div1hide, false);
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div id="hide">Click to hide.</div>

Related

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>

changing clicked element's style in array through javascript

my html code:
<div class="mydiv" onclick="clickonelement()">div1</div>
<div class="mydiv" onclick="clickonelement()">div2</div>
<div class="mydiv" onclick="clickonelement()">div3</div>
<div class="mydiv" onclick="clickonelement()">div4</div>
<div class="mydiv" onclick="clickonelement()">div5</div>
<div class="mydiv" onclick="clickonelement()">div6</div>
<!-- javascript code -->
function clickonelement(){
mydiv = document.getElementsByClassName("mydiv");
for(i=0; i<mydiv.length; i++){
mydiv.item(i).style.backgroundColor = "red";
mydiv[this].style.backgroundColor = "#fff";
}
}
css code
.mydiv{width:300px; height:30px;}
I want on onClick event to change clicked element's background to white and other elements background remain red in color but my code
mydiv[this].style.backgroundColor = "#fff";
is not working. please solve this problem in JavaScript only. I am in basic stage of JavaScript.
You need to pass a reference to the element that you want to refer to with this, e.g. onclick="clickonelement(this)":
function clickonelement(elem) {
mydiv = document.getElementsByClassName("mydiv");
for (i = 0; i < mydiv.length; i++) {
mydiv.item(i).style.backgroundColor = "red";
elem.style.backgroundColor = "#fff";
}
}
<div class="mydiv" onclick="clickonelement(this)">div1</div>
<div class="mydiv" onclick="clickonelement(this)">div2</div>
<div class="mydiv" onclick="clickonelement(this)">div3</div>
<div class="mydiv" onclick="clickonelement(this)">div4</div>
<div class="mydiv" onclick="clickonelement(this)">div5</div>
<div class="mydiv" onclick="clickonelement(this)">div6</div>
This is JS code for your HTML code, you need add addEventListener.
function clickonelement() {
mydiv = document.getElementsByClassName("mydiv");
for (var i = 0; i < mydiv.length; i++) {
mydiv[i].addEventListener('click', function() {
this.style.backgroundColor = "red";
this.style.backgroundColor = "#fff";
});
}
}
Here is just another way of achieving the same functionality.
Objective
To remove inline event handler
Use loop only once instead of looping over all the matched class name (mydiv) on every click.
Used javascript functions & concepts
querySelectorAll : - Used to select all matched elements with same class that is mydiv. It will return an nodelist containing all matched elements
forEach:- is an array method which used to loop over list.It accepts three arguments. For this case two will be enough.
addEventListener:- Is use to attach event to an element
Closures:These functions 'remember' the environment in which they were created.
Hope this snippet will be useful
//Get all the matched Elements
var matches = document.querySelectorAll("div.mydiv");
//Use an variable to rememeber previous clicked element
var prevIndex = -1; //
// Loop over the list
matches.forEach(function(item,index){
(function(i){ // A closure is created
item.addEventListener('click',function(){
// if any previous element was clicked then rest it's background
if(prevIndex !== -1){
matches[prevIndex].style.background="red";
}
// change background of current element
item.style.background="#fff";
// update prevIndex
prevIndex = i;
})
}(index))
})
Check this DEMO

Javascript get "this" class with onClick function

I want to create a function which manipulates an element with a specific class.
So far I have this:
function myFunc() {
var ball = document.getElementsByClassName('ball');
var myBall = 0;
myBall = ball[0].innerHTML; // HERE I NEED TO GET THE CURRENT BALL CLICKED
myBall[0].innerHTML = ++nr; // THE SAME HERE
}
The problem is that I don't know how to get the exactly div with the class:ball which was clicked. I know that myBall[0] is wrong. I need to set somehow the number representing the element clicked.
My HTML:
<div id="container">
<div class="ball" onclick="myFunc()">1</div>
<div class="ball" onclick="myFunc()">1</div>
<div class="ball" onclick="myFunc()">1</div>
</div>
Something like this
var elems = document.querySelectorAll('#container .ball');
for (var i=elems.length; i--;) {
elems[i].addEventListener('click', myFunc, false);
}
function myFunc() {
this.innerHTML = parseInt(this.innerHTML, 10) + 1;
}
<div id="container">
<div class="ball">1</div>
<div class="ball">2</div>
<div class="ball">3</div>
</div>

Change Div style onclick

I have 2 tabs at the top of a page. When one tab is clicked, I would like that tab to have an "active" class and the other tab to have an "inactive" class so that the user can see what tab is currently selected. How can I go about doing this with javascript/css?
<div class="tabActive">
Option 1
</div>
<div id="tabInactive">
Option 2
</div>
another non-jQuery solution could be the following that works with more than two div:
function changeClass(elClass) {
var divsLenght = document.getElementsByTagName("div").length;
for (var i = 0; i < divsLenght; i++) {
document.getElementsByTagName("div")[i].className = "tabInactive";
}
elClass.className = "tabActive";
}
Demo: http://jsbin.com/opetec/2
<div class="tabInactive" onclick="this.classname='tabActive'"></div>
if using jquery:
$("div.tabInactive").click(function() {
$("div.tabInactive").removeClass("tabActive");
$(this).addClass("tabActive");
});
here's a solution that doesn't use any jQuery! it does assume there is only 2 tabs thought.
http://jsfiddle.net/nYpV3/
<div id="tab1" onclick="setToActive(this, 'tab2');">
Option 1
</div>
<div id="tab2" onclick="setToActive(this, 'tab1');">
Option 2
</div>
function setToActive(me, otherId){
me.className='active';
document.getElementById(otherId).className='inactive';
}
Give your tabs a class of "tab"...
HTML:
<div class="tab">
...
</div>
<div class="tab">
...
</div>
JS:
function getByClass(_class, elem) {
var i, result = [], elems = document.getElementsByTagName("div"); //get the elements
for (i = 0; i < elems.length; i++) {
if (elems[i].className.indexOf(_class) !== -1) { //if the elements have the class passed in, add it to the result array
result.push(elems[i]);
}
}
return result;
}
var i, tabs = getByClass("tab", "div"); //get all divs with class tab
for (i = 0; i < tabs.length; i++) { //for each tab...
tabs[i].onclick = function() { //wire up it's click event...
//to clear the other tabs...
var j;
for(j=0; j < tabs.length; j++) {
tabs[j].className = tabs[j].className.replace(" active", "");
}
this.className += " active"; //where active is a class predefined in the CSS
};
}
http://jsfiddle.net/thomas4g/pqMq2/12/
Try this using jQuery
<div class="tab active">
Option 1
</div>
<div class="tab">
Option 2
</div>
<script>
$(function(){
$(".tab").live("click", function(){
$(".tab").removeClass("active");
$(this).addClass("active");
});
});
</script>
This is my guess:
$('.tabActive, #tabInactive').click(function() {
$(this).toggleClass('active');
}

javascript only - how to filter a specific div class?

I have many DIVs, let's say 100, split by categories like that :
<div id="div1" class="cat01">text</div>
<div id="div2" class="cat02">text</div>
<div id="div3" class="cat01">text</div>
<div id="div4" class="cat02">text</div>
<div id="div5" class="cat03">text</div>
<div id="div6" class="cat01">text</div>
And I want to filter a specific class
Let's say I click on a button "filter only cat02"
I then have only this on the page :
<div id="div2" class="cat02">text</div>
<div id="div4" class="cat02">text</div>
I do not have to use a class to define the categories, but it seems the appropriate solution...
Thanks you VERY much for your help!
EDIT : much clearer
Here is the file :
<div id="principal">
<div class="abc1 categ1">Text0</div>
<div class="abc5 categ3">Text0</div>
<div class="abc4 categ2">Text1</div>
<div class="abc7 categ1">Text0</div>
<div class="abc2 categ2">Text2</div>
<div class="abc4 categ3">Text0</div>
<div class="abc6 categ1">Text0</div>
<div class="abc7 categ2">Text3</div>
</div>
and I want this :
Text1
Text2
Text3
You can do something like this:
var list = document.getElementsByClassName('cat02');
for (var i = 0; i < list.length; i++) {
// this will remove the node from the page
list[i].parentNode.removeChild(list[i]);
// if you just want to hide it, you can do this:
// list[i].style.display = 'none';
}
Note that getElementsByClassName isn't supported by most browsers -- for those that don't, you may have to use a custom implementation such as the one here.
Update: If all your DIVs are direct children of a single DIV and they each contain only one class, it makes the task much simpler. You can skip getElementsByClassName and instead just iterate over the children:
function showOnly(parent, className) {
className = ' ' + className + ' ';
var e = parent.firstChild;
while (e != null) {
if (e.nodeType == 1) {
if ((' ' + e.className + ' ').indexOf(className) > -1)
e.style.display = 'block';
else
e.style.display = 'none';
}
e = e.nextSibling;
}
}
showOnly(document.getElementById('masterdiv'), 'cat02');
Edit: There were a couple of errors previously that I've fixed now. The indexOf comparison should be > -1 instead of > 0 and also the list of children includes empty text nodes (spaces between tags) that should be ignored, hence the check for e.nodeType == 1.
Seem like jQuery would help a lot here. You could just call $("div[class!='class02']") and get an array of items you want. Then, you could call .addClass('hidden') or whatever you need to do to the other items.
A brute force solution:
var list = document.getElementsByTagName('div');
for (var i = 0; i < list.length; i++) {
if (list[i].className != 'cat02') {
list{i].style.display = 'hidden';
}
}
Wrap this in a function to something like this:
function filterDivs(nameToFilter) {
var list = document.getElementsByTagName('div');
for (var i = 0; i < list.length; i++) {
if (!contains(list[i].className.split(' '), nameToFilter)) {
list{i].style.display = 'hidden';
}
}
}
EDIT:
using this function to search for strings in an array that I found here
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
With only 100 divs, it should run pretty quickly, but if you increase this amount a lot, it will become slow.
I also recommend that you don't remove items from a collection while iterating through it, that will cause you trouble. Hide them instead, or work with different collections.

Categories

Resources