Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I concat a string and a variable to select a DOM element in JavaScript?

Tags:

javascript

I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.

I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.

var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');

for(var i=0;i<4;i++){
 console.log(copy+i);
 console.log("copy"+i);
};

Ideally I would be able to select an element and style that via javascript.

Much appreciated
Thanks All.
Moe

like image 698
Moe-Joe Avatar asked Jun 07 '17 04:06

Moe-Joe


People also ask

How do you combine variables and strings?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.

Can you concatenate string and int in JavaScript?

You can directly add string and number in JavaScript, no need for a special method or typecasting. Just use a + (Adds two operands) OR += operator to Concatenate integer variable to a string variable.

Can you concatenate strings in JavaScript?

The concat() function concatenates the string arguments to the calling string and returns a new string.

What is the best way to concatenate strings in JavaScript?

The best and fastest way to concatenate strings in JavaScript is to use the + operator. You can also use the concat() method.


1 Answers

Agree with @jaromanda-x:

var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
   console.log(window['copy'+i]);
};

Or you can use more simple example, like:

for (var i=1; i<4; i++) {
    var name = 'copy' + i;
    console.log(document.getElementById(name));
};

Or even:

for (var i=1; i<4; i++) {
    console.log(document.getElementById('copy' + i));
};
like image 106
cn007b Avatar answered Oct 21 '22 09:10

cn007b