Add class to elments with same matching class as per clicked element - javascript

I need to add an .active class to any button which matches any of the classes as per the div I am clicking:
<button class="valueA"></button>
<button class="valueB"></button>
<button class="valueC valueB"></button>
<div class="DYNAMIC CLASS"></div>
$("div.valueB").on("click", function() {
...
});
The result should be:
<button class="valueB active"></button>
<button class="valueC valueB active"></button>
I tried using .each() but I'm stack with the comparison of the classes.
The thing is that my div has dynamic class just as well as those buttons, so I don't know what matches until they are in the DOM.

One version is to create a click function for every single class that you have in your document. This would look something like this:
$('.valueA').click(function() {
$('.valueA').addClass('active')
})
$('.valueB').click(function() {
$('.valueB').addClass('active')
})
$('.valueC').click(function() {
$('.valueC').addClass('active')
})
This is repetitive code however and should be avoided. So instead you can create a function that adds click handlers to all buttons (that's the example I wrote) and then retrieves the classes attached to the element. It then loops over the array of classes and adds to every element with that class another one.
$('button').click(function() {
var classes = $(this).attr('class').split(' ')
classes.forEach(function(elem) {
$('.' + elem).addClass('active');
})
})
Now if you want to limit the application of said class then you add the element type that the class should be applied to before the .
$('button.' + elem).addClass('active');
or
$('div.' + elem).addClass('active');

You need to get class name of div using .attr() and use class name in selector.
$("div").on("click", function() {
var className = $(this).attr("class");
$('button.'+ className).addClass('active');
});
.active { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="valueA">A</button>
<button class="valueB">B</button>
<button class="valueC valueB">CB</button>
<div class="valueB">B</div>

You don't need to use .each(). You can do it like following.
$("div").on("click", function() {
$('button.active').removeClass('active');
$('button.' + this.className).addClass('active');
});
.active {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="valueA">A</button>
<button class="valueB">B</button>
<button class="valueC valueB">C</button>
<div class="valueA">DIV A</div>
<div class="valueB">DIV B</div>
<div class="valueC">DIV C</div>

Get the name of your divs class and add your .active class to all of your buttons by using the corret selector $('button.valueB').
So a dynamic solution could look like this
$("div.valueB").on("click", function(e) {
var className = e.target.className;
$('button.' + className).addClass('active');
});
Demo

Related

Is there a way to select an element by class even though the class has been removed?

At the start I don't want .screen-text-page2 visibile, only after .screen-text-button-page1 is clicked
$('.screen-text-page2').removeClass("screen-text-page2");
$('.screen-text-button-page1').click(function() {
$('.screen-text-page2').addClass("screen-text-page2");
});
.screen-text-page2 {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="screen-text-button-page1">Button</button>
<div class="screen-text-page2">Div with class screen-text-page2</div>
Short answer: Yes
The removeClass method is not a state... once you run it the class is removed and the element can accept any new class, including the same one.
If you want to re-add the class, then just add it again.
$("#ele").removeClass(".myClass");
$("#ele").addClass(".myClass");
is completely valid
Yes, but because you're removing the class, you won't be able to select it again via $('.screen-text-page2'). But if you save the selected element as a variable, you can reference it again without needing to reselect it using the class.
let page2 = $('.screen-text-page2');
$(page2).removeClass("screen-text-page2");
$('.screen-text-button-page1').click(function() {
$(page2).addClass("screen-text-page2");
});
.screen-text-page2 {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="screen-text-button-page1">Button</button>
<div class="screen-text-page2">Div with class screen-text-page2</div>
Another way to do something like this is to add another class before removing .screen-text-page2, and then reselecting the element using this placeholder class. But in my opinion, that's just more steps than the above example.
$('.screen-text-page2').addClass("screen-text-page2-placeholder");
$('.screen-text-page2').removeClass("screen-text-page2");
$('.screen-text-button-page1').click(function() {
$('.screen-text-page2-placeholder').addClass("screen-text-page2");
});
.screen-text-page2 {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="screen-text-button-page1">Button</button>
<div class="screen-text-page2">Div with class screen-text-page2</div>

Use variable as selector in function

On click, I want to get the name of the closest div and then look for all div's, that have this name attribute and add a class to them.
Here is my code:
HTML:
<div class="wrapper">
<div class="container" name="button1">
<div class="button">this is p #1</div>
</div>
</div>
<div name="button1">
somewhere else
</div>
JS:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).closest('.container').attr('name');
$("div[name=attrname]").each(function() {
$(this).addClass("classtobeadded");
});
});
But it is not working. So, how can I use the variable in here:
$("div[name=attrname]").each(function()
Here is the fiddle:
There's a few issues with your logic. Firstly the .container element does not have the name attribute, the .button does, so you don't need to use closest(). Secondly, you need to concatenate the actual name value in to the selector. Lastly div elements do not have a name attribute so the HTML is invalid. If you want to store custom meta-data on an element use a data attribute instead.
Also note that you don't need the each() loop, you can just call addClass() on the collection selected with the data-name attribute. Try this:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).data('name');
$('div[data-name="' + attrname + '"]').addClass("classtobeadded");
});
.classtobeadded {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="button" data-name="button1">this is p #1</div>
</div>
</div>
<div data-name="button1">
somewhere else
</div>
You have to concatenate it properly,
$(`div[name=${attrname}]`).each(function() {
And by the way, when looking at your code there is no attribute available in the closest div with a class .container. Check that as well.
$("div[name=" + attrname + "]").each(function() {})
or
$(`div[name=${attrname}]`).each(function() {})

jQuery check divs has a class and unwrap if no other class

I have two div's and what I am trying to do is loop through all the divs to check if the div has a class jsn-bootstrap3, I'm also trying to check to see if the div has any other classes, if it doesn't then I'd like to remove the jsn-bootstrap3 div so that the child content is whats left.
<div class="jsn-bootstrap3">
<div class="wrapper">
Div one
</div>
</div>
<div class="jsn-bootstrap3 block">
<div class="wrapper">
Div two
</div>
</div>
$('div').each(function() {
if ($(this).hasClass()) {
console.log($(this));
var class_name = $(this).attr('jsn-bootstrap3');
console.log(class_name);
}
});
jsFiddle
You can try something like
$('div.jsn-bootstrap3').removeClass('jsn-bootstrap3').filter(function () {
return $.trim(this.className.replace('jsn-bootstrap3', '')) == ''
}).contents().unwrap();
Demo: Fiddle
use the class selector to find div's with class jsn-bootstrap3 because we are not goint to do anything with others
use filter() to filter out div's with any other class
use unwrap() with contents() to remove the wrapping div

jQuery toggle 3 Div

I wanna toggle 3 div.
In the start situation I have the first div that is not trigger able for the clic because its ID.
When I click the second or third div (triggered), the DIV clicked have to become unclickable and the others 2 clickable.
I attach my live example:
http://jsfiddle.net/YV3V5/
HTML:
<div id = "not-selectable" class = "btn1">Div 1</div>
<div id = "selectable" class = "btn2">Div 2</div>
<div id = "selectable" class = "btn3">Div 3</div>
JAVASCRIPT:
$( "#selectable" ).click(function(e) {
var className = $(this).attr('class');
alert(className);
if (className == "btn1") {
$("btn1").attr("selectable","not-selectable");
$("btn2").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn2") {
$("btn2").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn3") {
$("btn3").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn2").attr("not-selectable","selectable");
}
});
In this situation when I click the second DIV, it should became unclickable....but nothing happens.
Thanks for you're help!
You have several errors in your code. The most important being that IDs should be unique. Secondly you are trying to assign values to attributes "selectable" and "not-selectable". These attributes do not exist.
If you lay out your markup correctly, you could do this pretty simple. I would suggest something like this:
HTML
<div class="buttons">
<div class="button">Div 1</div>
<div class="button selectable">Div 2</div>
<div class="button selectable">Div 3</div>
</div>
jQuery
$( ".buttons" ).on("click",".selectable",function(e) {
$('.button').addClass('selectable');
$(this).removeClass('selectable');
});
Can be tested here
(I've added a parent element to simplify event delegation in jQuery.)
there is no attribute called selectable for html tags.
when you write $("btn3").attr("selectable","not-selectable"); it means set the selectable attribute of btn3 to value 'not-selectable'.
also as btn3 is a class you should have written $('.btn3') instead of $('btn3')
WORKING DEMO http://jsfiddle.net/YV3V5/23/
There was a lot wrong with your code :
1) using duplicate id's : Id's must be unique , one per page. Classes do not have to be unique. So I changed around your id's and classes.
2) you should change classes with addClass/removeClass/or toggleClass
3) you shouldn't use a class your removing as the trigger of the click function, so I gave them all a same class of btn.
html :
<div id="btn1" class="not-selectable btn">Div 1</div>
<div id="btn2" class="selectable btn">Div 2</div>
<div id="btn3" class="selectable btn">Div 3</div>
css I added background of blue for selectable and red for not-selectable so easier to visualize what's happening:
.selectable {
background: blue;
}
.not-selectable {
background: red;
}
jquery :
$(document).ready(function () {
$(".btn").click(function (e) {
var id = $(this).attr('id');
if (id == "btn1") {
$("#btn1").removeClass("selectable").addClass("not-selectable");
$("#btn2").addClass("selectable").removeClass("not-selectable");
$("#btn3").addClass("selectable").removeClass("not-selectable");
} else if (id == "btn2") {
$("#btn2").removeClass("selectable").addClass("not-selectable");
$("#btn1").addClass("selectable").removeClass("not-selectable");
$("#btn3").addClass("selectable").removeClass("not-selectable");
} else if (id == "btn3") {
$("#btn3").removeClass("selectable").addClass("not-selectable");
$("#btn1").addClass("selectable").removeClass("not-selectable");
$("#btn2").addClass("selectable").removeClass("not-selectable");
}
});
});
.attr() sets the attribute to the tags. So like you would get <div non-selectable='selectable'> for that code. Here is the documentation. I would use .removeClass() and .addClass() though there might be a more efficient way.

Button show div without deleting the previous div

So,I have 8 buttons. Each one shows a div when it's pressed.The problem is that when I press multiple buttons , all of them show their divs and don't delete the previous ones. What can I do?
Html:
<button id ="btn1" >a</button>
<button id ="btn2">b</button>
<button id ="btn3">c</button>
<button id ="btn4">d3</button>
<button id ="btn5">e 4</button>
<button id ="btn6">f 5</button>
<button id ="btn7">g 6</button>
<button id ="btn8">h 7</button>
<div id="story">asdaasdasdasdadsasdsds</div>
<div id = "z2">asdaasdadsd</div>
<div id = "z3">asdasdasdad</div>
<div id = "z4">asdasdasdad</div>
<div id = "z5">asdasdasdad</div>
<div id = "z6">asdadsdaad</div>
<div id = "z7">asdads</div>
CSS:
#z1,
#z2,
#z3,
# z4,
#z5,
#z6,
#z7
{ display: none; }
JQuery:
$(function() {
$('#btn1').on('click', function() {
$('#story').fadeToggle(400);
});
$('#btn2').on('click', function() {
$('#z1').fadeToggle(700);
});
$('#btn3').on('click', function() {
$('#z2').fadeToggle(700);
});
$('#btn4').on('click', function() {
$('#z3').fadeToggle(700);
});
$('#btn5').on('click', function() {
$('#z4').fadeToggle(700);
});
$('#btn6').on('click', function() {
$('#z5').fadeToggle(700);
});
$('#btn7').on('click', function() {
$('#z6').fadeToggle(700);
});
$('#btn8').on('click', function() {
$('#z7').fadeToggle(700);
});
});
You can add a class to your div "divToHide" for instance and call
$('.divToHide').hide();
in your click method
here is a fiddle :http://jsfiddle.net/U5PEu/1/
You by the way have an extra space into you css between # and z4
You're not hiding the others because you're not doing anything with them. Try changing all of your on click handlers to be like this:
$('#btn1').on('click', function() {
// hides currently shown divs
$('.visible').removeClass('visible').fadeOut(700);
// shows div in question, and adds a class that can be queried later
$('#story').addClass('visible').fadeIn(400);
});
The "visible" class that is added can be used to collect and remove any visible divs (or any element, really), regardless of what showed them.

Categories

Resources