Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 634
gogachinchaladze Avatar asked Feb 27 '14 12:02

gogachinchaladze


People also ask

What data type does document getElementById return?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

What is document getElementById () value?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.

What is the syntax of getElementById ()? *?

What is the syntax of getElementById ()? JavaScript – getElementById() JavaScript getElementById() – In this tutorial, we shall learn to access an HTML DOM element by its unique id. To access an HTML DOM element with the help of its id value, use document. getElementById(<id_value>) method.


2 Answers

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

like image 71
Alex Avatar answered Oct 28 '22 03:10

Alex


Yes, you can. Just use

curr = 'rook';

(without the extra quotes)

like image 44
crates_barrels Avatar answered Oct 28 '22 01:10

crates_barrels