Home > Back-end >  Correct syntax for iterating through elements selected via data attribute
Correct syntax for iterating through elements selected via data attribute

Time:08-08

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);

}

CodePudding user response:

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);
    }

CodePudding user response:

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);

CodePudding user response:

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>

  • Related