David McCulloch
David McCulloch

Reputation: 21

Template Literals formatting / syntax issue

I'm struggling because I have run this for loop with jQuery, but I can't get any output and I believe it is because my syntax for my template literals is messing up my code. I don't know how to write that line properly, I've tried it many ways, but I can't get it to come back properly. Thanks for your help!

let characterArray = ['a', 'b', 'c', 'd'] //test
let propertiesArray = ['abc', 'def', 'ghi'] //test

function data() {
    for (let i=0; i < characterArray.length; i++) {
        for(let j=0; j < propertiesArray.length; j++) {
            `$('#${characterArray[i]}').attr('data-${propertiesArray[j]}', 
            ${characterArray[i]}.${propertiesArray[j]})`;              
        }    
    }
}

Upvotes: 2

Views: 52

Answers (2)

M0nst3R
M0nst3R

Reputation: 5283

JavaScript template literals are a way to construct complex/multiline strings, not statements. You can incorporate them within your jQuery statements as follows:

let characterArray = ['a', 'b', 'c', 'd'] //test
let properties = ['abc', 'def', 'ghi'] //test

function data() {
    for (let i=0; i < characterArray.length; i++) {
        for(let j=0; j < properties.length; j++) {
            $(`#${characterArray[i]}`).attr(
                `data-${properties[j]}`,
                `${characterArray[i]}.${properties[j]}`
            );              
        }    
    }
}

Upvotes: 1

Taplar
Taplar

Reputation: 24965

`$('#${characterArray[i]}').attr('data-${properties[j]}', ${characterArray[i]}.${properties[j]})`;

Should be

$(`#${characterArray[i]}`).attr(`data-${properties[j]}`, `${characterArray[i]}.${properties[j]}`);

Each part that you want to transform into a string should be in the template, not the entire command.

Upvotes: 0

Related Questions