简体   繁体   中英

JavaScript - Find ID that matches data attribute value

I have a variable that finds the data attribute of an element that is clicked on in a callback function:

var dropdown = document.getElementsByClassName('js-dropdown');

 for (i = 0; i < dropdown.length; i++) {

   dropdown[i].addEventListener("click", callBack (dropdown[i]));

 }

function callBack (i) {

 return function () {

  var thisDropdown = i.getAttribute('data-dropdown');

  //rest of the code here

  }

}

I am basically trying to do this

$('#' + thisDropdown ).toggleClass('is-active');

...but in vanilla JS.

This works fine using jQuery however I would like a vanilla version.

So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class.

I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for.

I've been trying to do something along the lines of

var idValue = document.getElementById(thisDropdown);

Then

var findId= idValue + thisDropdown;

findId.toggleClass('is-active');

Obviously that does not work the same way the jQuery statement works... any ideas?

Ignore the toggleClass method! Some of you may find this contradictory as I want vanilla JS.

To replace $('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList . Like this:

const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");

I like @kamyl's answer, but you might need backward compatibility. For that, see if you can find a polyfill.

If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; add if not, remove if so...then array.join(" ") and replace the class attribute with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM