'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.
Solution 1:[1]
Yes, you can. Just use
curr = 'rook';
(without the extra quotes)
Solution 2:[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';
Solution 3:[3]
You can even do stuff like this:
function mark(yy) {
for (var ii = 0; ii < 7; ii++ ) {
if ( ii == yy ) {
document.getElementById("b"+ii).style.fontWeight = "bold";
}
...
But be careful of your loop limits to be sure you have a matching id. I just spent hours trying to figure out why ("b"+ii) was getting error and finally realized that the error was being caused by exactly that. duh...
Solution 4:[4]
Yes, Mate, you can.
You can use a variable as the argument for any function. That's just how functions work -- they don't care where the argument comes from. You should define curr outside those functions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | crates_barrels |
| Solution 2 | Alex |
| Solution 3 | Howard_L |
| Solution 4 | Grab The APK |
