Home > database >  Return class that matches element from list
Return class that matches element from list

Time:07-24

I have a nodelist of elements in js that were collected by querying many classes and then a "for" statement that loops through the list. What I need is a quicky one-line way to return what class each element was selected by within the loop so I can perform an action based on that. Here is my code blip:

var nodeList = document.querySelectorAll(".class1, .class2, .etc...");
for (var i = 0; i < nodeList.length; i  ) {
    var classOfCurrentDiv = [...]
    //perform action using classOfCurrentDiv
}

I know I can do something like

if (nodeList[i].classList.contains(class1)) {
    //perform code
}

and repeat that for each class, or do a comparison of the element's classlist and the list of classes I'm searching for, but all I need to do is insert the name of the class into a string, so I'd prefer a single line solution to obtain the class that returned the element in the query. The class that returned the element may not be that element's only class which is why I can't just pull the element's classlist.

This is probably very simple and I'm just blanking on how to do it, but let me know. The list of queried classes will be hardcoded and each element's classlist will only contain one of the queried classes if that helps.

Thanks!

CodePudding user response:

Something like that ?

const classList = [".ps-fixed", ".class1", ".class2"]

const nodeList = document.querySelectorAll(classList)

nodeList.forEach((node) => {
  classList.forEach((ClassMatch) => {
    if (node.classList.contains(ClassMatch.slice(1))) { //slice 1 to remove the "." before the class names in the array
      console.log(node)
    }
  })
});

CodePudding user response:

You can use Element.matches to do this with a 1 liner.

Element.matches(selector) lets you specify a css selector to an element and it will return if the element is matched by the selector. Since your selector works out to be a comma separated list of classes, you can find which class matched the particular element by splitting the selector on commas to an array, loop thru that array as each class via filter and filter out elements that don't match. Full example below:

function classOfCurrentDiv(div, selector) {
    return selector.split(", ").filter(_class => div.matches(_class))[0];
}

const selector = ".class1, .class2, .class3";
const nodeList = document.querySelectorAll(selector);
for (let i = 0; i < nodeList.length; i  ) {
    console.log("selector of element "   i   ":", classOfCurrentDiv(nodeList[i], selector));
}
<div ></div>
<div ></div>
<div ></div>

  • Related