Can I use a string variable in document.getElementById ()?

here is my code:

function figureSelector () {
    document.getElementById("rook").onclick = function  () {
        curr = '"rook"';
    };
};

function moveLine(){
    document.getElementById("upButton").onclick = function() { 
            document.getElementById(curr).style.top = document.getElementById(curr).offsetTop - getPix() * 62  + "px"; 
            counter= counter + getPix();
    }; 

I want to write a universal function for moving a chess piece. All I want is when you click on the chess piece and then press the up button, it should go up.

+4
source share
2 answers

Yes, you can. Just use

curr = 'rook';

(without extra quotes)

+3
source

Yes you can use String variable:

HTML:

<div id="name" style="width:300px;height:300px;background:red"></div>

JavaScript:

var b = 'name';
document.getElementById(b).innerHTML = 'none';

jsfiddle here

+4
source

Source: https://habr.com/ru/post/1529202/


All Articles