I am using facetwp plugin for Wordpress for filtering posts. Each facet outputs its options with markup like this...
<div class="facetwp-radio" data-value="blue"> ... </div>
When an option is selected the class .checked is added.
So on a given page I might have something like this..
<div class="facetwp-radio .checked" data-value="blue"> ... </div>
<div class="facetwp-radio" data-value="red"> ... </div>
<div class="facetwp-radio .checked" data-value="green"> ... </div>
<div class="facetwp-radio" data-value="brown"> ... </div>
<div class="facetwp-radio .checked" data-value="yellow"> ... </div>
I need to cycle through all these elements, fine the ones that have the .checked class, take their data-value and find other elements on the page that have classes equal to the data-value and add the .checked class to them.
I have working code for a single instance..
if ($('.facetwp-facet .checked[data-value="blue"]').length > 0) {
$('.blue').addClass('checked');
} else {
$( ".blue" ).removeClass( "checked" );
}
How can I amend this code to 'cycle' dynamically through all of the possible combinations?
CodePudding user response:
If I am understanding your question, you are looking to iterate through the set of all checked radios, and then obtain an attribute for each element in that set. Then you seek to find all elements that have those values as a class.
$(".facetwp-radio .checked").each(function() {
var dv = $(this).attr("data-value");
var classSelector = "." dv;
var elementList = $(classSelector);
<Do whatever you want to do with that element set>
});
CodePudding user response:
$('.facetwp-radio').each(...)
to iterate all elements. Not common practice to have dot inside css class name.
Demo at https://codepen.io/ProGu/pen/jOLqrZP
$('.facetwp-radio').each(function() {
if ($(this).hasClass('.checked')) {
$('.' $(this).data('value')).addClass('.checked');
} else {
$('.' $(this).data('value')).removeClass('.checked');
}
});