Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Target/style an element’s attributes with JavaScript

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 class="radio-wrapper" 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading