Home > Enterprise >  Target/style an element’s attributes with JavaScript
Target/style an element’s attributes with JavaScript

Time:07-25

I'm attempting to change the style of the div element below using JavaScript, but by using its attribute as the selector instead of the class:

<div  data-option-method="Option-A">

For example, I'm able to achieve the desired effect with the following CSS:

.radio-wrapper[data-option-method="Option-A"] { display: none; }

But I'm not having any luck when I attempt the same in the JS:

document.getElementsByClassName(".radio-wrapper[data-option-method="Option-A"]").style.display = "none";

I'm sure this is a fairly simple one, but I'm struggling to research a clear answer, greatly appreciate any suggestions!

CodePudding user response:

First of all, you have a clear syntax error. Your browser console is undoubtedly pointing this out to you. Always check the console for errors.

Since your string contains double-quotes, use single-quotes for the string itself:

'.radio-wrapper[data-option-method="Option-A"]'

Aside from that, document.getElementsByClassName is the wrong function to use here. What you have isn't a class name, it's a more complex selector. document.querySelector can find the element based on that:

document.querySelector('.radio-wrapper[data-option-method="Option-A"]').style.display = "none";

Alternatively, if there are multiple matching elements and you want to target all of them, use querySelectorAll and iterate over the results:

let elements = document.querySelectorAll('.radio-wrapper[data-option-method="Option-A"]');
for (let el of elements) {
  el.style.display = "none";
}

CodePudding user response:

The problem is that isn't the class name. ([data-option-method="Option-A"] is an attribute) Try it with:

document.querySelector('.radio-wrapper[data-option-method="Option-A"]')

If you want to select multiple, use querySelectorAll but bare in mind that returns an array.

Also watch out for the `, ", and ' in strings, either escape them with a " or combine them as I did.

  • Related