remove class to selected variants with JS

Viewed 53

Hi there im making some adjustments to my product page, where i want to show/hide selected variants.

filterMedia() {
const variantSwatches = document.querySelectorAll("[data-variant-color]");
for (const variant of variantSwatches) {
  variant.style.display = "none";
}

var selected_variant = this.currentVariant.featured_media.alt;
var selected_attribute =
  '[data-variant-color="' + selected_variant + '"]';

if (selected_variant == selected_variant) {
  console.log(selected_attribute);
}

I created this part of code with vanilla JS, first of all i add style="none" to all div with data-variant-color, then i get selected variant:

console.log(selected_attribute);

enter image description here

enter image description here

Just need to remove style="none" of all variants doesn't be == to selected variant.

I'm a little bit confused, if anyone can help me with this :)

EDIT V2

    updateVariantImage() {
const dataVariants = document.querySelectorAll("[data-variant-color]");
dataVariants.forEach((dataVariant) => {
  dataVariant.style.display = "none";
});

var selected_variant = this.currentVariant.featured_media.alt;
var selected_attribute = '[data-variant-color="' + selected_variant + '"]';

if (selected_variant == selected_variant) {
const getVariants = document.querySelector(selected_attribute);
console.log(getVariants);
}

} enter image description here

1 Answers

you need to use querySelectorAll instead of querySelector it returns the 1st instance. so you need to loop on the element that meets the condtions like this

const getVariants = document.querySelectorAll(selected_attribute);
getVariants.forEach(function(ele){
  ele.stle.display = 'block';
});

You can read more about querySelector and querySelectorAll here

Related