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

151
Visualizações
Correct syntax for iterating through elements selected via data attribute

So I've got the following, which works fine:

var sidebar1 = document.querySelector("[data-language-key='sidebar-1']").innerHTML;

But for scalability purposes, I'd like to create an array sidebar and use a for loop to store all the sidebar-X text values. I have written out something already but I can't get the syntax to work.

var sidebar = [];

for (var i = 1; i <= 6; i++) {

  sidebar.push(document.querySelector(`[data-language-key=`
    'sidebar-' + i ``).innerHTML);

}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The key value in the querySelector should have as a string. This kind of error occurs usually while coding with DOM. Let me show you the result of your code.

sidebar.push(document.querySelector(`[data-language-key=`
    'sidebar-' + i `]`).innerHTML);

This will be read like,

//if i = 0
sidebar.push(document.querySelector(`[data-language-key=sidebar-0]`).innerHTML);

HTML tags has attribute's value as string so the querySelector should have a string with quotes.

//if i = 0
sidebar.push(document.querySelector(`[data-language-key="sidebar-0"]`).innerHTML);

So to let the querySelector works use like,

sidebar.push(document.querySelector(`[data-language-key="`
    'sidebar-' + i `"]`).innerHTML);
about 4 years ago · Juan Pablo Isaza Relatório

0

Don't specify the value of [data-language-key] because you'll have to edit your code if you add new sidebar elements. Just use that selector but with querySelectorAll to pick them all up. Then map over the node list (after coercing it to an actual array), and return each element's text content.

const selector = '[data-language-key]';
const els = document.querySelectorAll(selector);

const sidebar =  Array.from(els).map(el => {
  return el.textContent;
});

console.log(sidebar);
<aside>
  <div data-language-key="1">one</div>
  <div data-language-key="2">two</div>
  <div data-language-key="3">three</div>
  <div data-language-key="4">four</div>  
</aside>

about 4 years ago · Juan Pablo Isaza Relatório

0

You just have to make a variable everytime in iteration:

var sidebar = [];
    for(var i=0;i<6;i++){
     var side = document.querySelector('[data-language-key = "sidebar-'+i+'"]').innerHtml();
    sidebar.push(side);
    }
about 4 years ago · Juan Pablo Isaza 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