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

I tried this question but no luck. Probably because I ask not so. Any help is greatly appreciated.

I have variables copy1, copy2etc. I want to iterate over them and select each of them to check if this content contains a certain number of characters. When I use any changes below, it will either hide the error or display a line 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 are using javascript.

Great value Thank you all.
Mo

+6
source share
3 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 a simpler example, for example:

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

:

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

, DOM

let copies = {
 1 : document.getElementById('copy1'),
 2 : document.getElementById('copy2'),
 3 : document.getElementById('copy3')
}

for (let [key, prop] of Object.entries(copies)) {
  console.log(key, prop)
}

console.log(copies[1], copies[2], copies[3]);

use, .querySelector()

let n = 1;
let copy1 = document.querySelector(`[id^=copy][id$='${n}']`); // `#copy1`
let copy2 = document.querySelector(`[id^=copy][id$='${++n}']`); // `#copy2`

for (let i = 1; i < 4; i++) {
  console.log(document.querySelector("[id^=copy][id$=" + i + "]"));
}
+1

Since no one has yet addressed your claim of a “certain number of characters,” I thought I would.

You can always use jQuery or write your own $ method, which works like the document.getElementById () function.

Here is jsfiddle to see it in action.

HTML

<div id="copy1">01234</div>
<div id="copy2">012345678</div>
<div id="copy3">0123456789 0123456789</div>

Javascript

// Isn't this just a brilliant short-cut?
function $(id) {
   return document.getElementById(id);
}

for (let i=1; i<4; i++){
   let obj = $('copy' + i);
   let value = (obj) ? obj.innerText : '';
   console.log('value.length:', value.length);
};
+1
source

All Articles