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

78,985

Solution 1

Yes, you can. Just use

curr = 'rook';

(without the extra quotes)

Solution 2

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

Share:
78,985
gogachinchaladze
Author by

gogachinchaladze

Updated on December 17, 2020

Comments

  • gogachinchaladze
    gogachinchaladze over 3 years

    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 an universal function for a chess piece to move. All I want is, when one clicks the chess piece, and then presses the up button, it must go up.