Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
Return class that matches element from list

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!

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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 class="class1 foo"></div>
<div class="class3 bar"></div>
<div class="class2 baz"></div>

about 4 years ago · Santiago Trujillo Relatório

0

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)
    }
  })
});
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda