Proper syntax for looping through elements selected by a data attribute

I have a working code snippet as shown below:

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

However, I am looking to enhance the scalability by creating an array sidebar and using a for loop to store all the text values of sidebar-X. I have attempted to write something for this purpose but struggling with the syntax.

var sidebar = [];

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

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

}

Answer №1

Creating a new variable during each iteration is essential:

let widgets = [];
    for(let j=0;j<8;j++){
     let widget = document.querySelector('[data-translation-key = "widget-'+j+'"]').innerText;
    widgets.push(widget);
    }

Answer №2

When using querySelector, it's important for the key value to be in the form of a string. This error commonly occurs when working with the DOM. Let me demonstrate the outcome of your code.

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

This can be interpreted as,

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

HTML tags require attribute values to be strings, so ensure that the querySelector includes a string enclosed in quotes.

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

To make the querySelector function properly, modify it like this,

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

Answer №3

It is recommended not to hard-code the value of [data-language-key] as it may require code modifications for new sidebar elements in the future. Instead, utilize this selector with querySelectorAll to capture all elements. Subsequently, you can use map on the node list (after converting it to an array) to retrieve 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

Manipulating the Document Object Model (DOM) in Google

I typically implement this method to ensure that users adhere to the validation rules before submitting. <a class="waves-effect waves-light btn disabled">Submit</a> But, I recently discovered that by simply removing the disabled class using G ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Create a link for editing in a data table that can filter based on multiple column values and also enable global search on specific custom

How can I generate an edit link with a function that requires multiple parameters extracted from different data columns received via ajax? I have come across the render callback, but it seems to only return one column value at a time and my requirement is ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

Activate Span element when image is clicked

To show and hide different span tags when clicking on specific images, you can use the following jQuery script: $("#img1").on('click', function() { $("#div1").fadeIn(); $("#div2,#div3").fadeOut(); }); $("#img2").on('click', functio ...

Tips for accessing a variable located in a different directory

I'm facing some confusion regarding creating a global variable that can be accessed in another file. Currently, I have a chat and login folder setup. Within the login folder, there are three possible users to choose from. When a user clicks on one of ...

Changing the colors of multiple buttons in a React Redux form: a step-by-step guide

When using Redux Form Wizard on the second page, I have two buttons that ask for the user's gender - Male or Female. The goal is to make it so that when a user clicks on either button, only that specific button will turn orange from black text. You ...

Develop a form that relies on multiple requests made through AJAX

I am attempting to create a form that requires 2 ajax calls. The first call retrieves information about a ranking that is then displayed in the form using the following code: $.ajax({ method: "GET", url: base_url + "/ranking/getranktoedit/" + rank ...

Showing the result of a backend script on the current page using PHP

I currently have a PHP web application that involves submitting data to a backend pipeline, also written in PHP. This pipeline consists of an external script that my application accesses using the 'exec' PHP function. The pipeline follows a multi ...

Is there a way to execute a node script via command line sans the need for installation and external packages?

Is there a way to execute a node script from the command line during development without actually installing anything, but still having access to installed packages using npm install <...>? When I try node ./bin/my_script.js, the script does not reco ...

Adding Kafka-node Consumer Messages to an Array

Recently, I've delved into the realm of JavaScript and have been in the process of learning its intricacies. I've encountered a piece of code that goes as follows: Consumer = kafka.Consumer, client = new kafka.KafkaClient(); module.exports = t ...

Retrieve the position of my dropdown menu using jQuery

Currently, I am working on creating a jQuery drop-down menu that can be used anywhere on my page in a dynamic manner. The goal is to make it flexible so that each element containing the trigger class will be positioned perfectly and trigger the drop-down w ...

How can I automatically disable certain checkboxes when a specific radio button is selected?

Looking to disable certain checkboxes when a specific radio button is selected. For instance, selecting the first radio button with the id="pz1" should disable checkboxes with matching id values from the thisToppings array. Each radio button cor ...

Methods for performing a task on a class automatically, while ensuring it is only executed one time

My goal is to create a system where all classes derived from a base class automatically have a specific operation performed when they are loaded, but only once during the program's execution. I want to simplify the process for the person creating the ...

Ways to customize the bootstrap-datetimepicker to display time in 15-minute increments

Here is my code in JavaScript to increment by minutes at a 1-hour interval: fillMinutes = function () { var table = widget.find('.timepicker-minutes table'), currentMinute = viewDate.clone().startOf('h'), ...

Dealing with prompt boxes in Robot Framework: A Guide

Currently, I am utilizing the Robot Framework in conjunction with Selenium2Library for automating tests on websites. During one particular scenario, a prompt box appeared (similar to an alert but containing an input field). The challenge is that Robot Fram ...

Troubleshooting problem with modifying Bootstrap button styling and hover effects

When creating a navigation menu with Bootstrap, I decided to change the buttons from the primary class to inverse. I then went on to further customize the inverse class using inline CSS to match my specific look and feel requirements. .btn-inverse { b ...

What steps can I take to avoid horizontal scrolling on mobile due to a table overflowing?

My website displays a table within a bootstrap container, row, and column. While everything looks good on larger screens, the content within the table is causing a horizontal scroll on smaller screens, making the footer look distorted. This results in a me ...

How to prompt the browser to download a file with a specific name using node.js and express

I've created a node/express website as part of my university project. It allows users to search for a specific law ID, which then displays a table with various files in different formats and languages related to that ID. I am using the "http-proxy" mo ...