0

My problem: i want to add 1 to a variable (row) within a String.

This won't work:

function checkIfWon(col, row, color) {
         alert(document.querySelector('[col="' + col + '"][row="' + row+1 + '"]').getAttribute("color"));
}

Error in Console:

Uncaught TypeError: Cannot read property 'getAttribute' of null

But this code gives me the color:

function checkIfWon(col, row, color) {
         let newRow = row+1;
         alert(document.querySelector('[col="' + col + '"][row="' + newRow + '"]').getAttribute("color"));
    }

so how can i add row + 1 within the String? Thanks.

Peter
  • 101
  • 1
  • 8
  • your issue is that `row="' + row+1 + '"]` isn't adding 1 to row, it's concatenating – Nick Parsons Mar 28 '20 at 09:25
  • @NickParsons I know, so how I can I add 1 to row in my String? – Peter Mar 28 '20 at 09:26
  • 3
    try `... [row="' + (row+1) + '"]'` – Nick Parsons Mar 28 '20 at 09:27
  • why not just use ` `[col="${col}"][row="${row+1}"]` ` template string – xdeepakv Mar 28 '20 at 09:29
  • @NickParsons (row+1) solved my Problem, thx – Peter Mar 28 '20 at 09:31
  • In javascript `1 + 1 == 2 // addition '1' + '1' == '11' // concatenation 1 + '1' == '11' // concatenation 1 + 1 + '1' == '21' // addition, concatenation 1 + 1 + '1' + 1 + 1 == '2111' // addition, concatenation, concatenation` i.e, Once String concatenation starts, everything ahead is concatenated as string. – Rohit Kaushal Mar 28 '20 at 09:32
  • You don't exactly have to use template litterals but it's cleaner that way. Alternatively you could just use `(...)` between the math you want to use. – Jens Ingels Mar 28 '20 at 09:34

1 Answers1

0

You can use Template Strings

for contact

alert(document.querySelector(`[col="${col}"][row="${row}1"]`).getAttribute("color"));

for sum

alert(document.querySelector(`[col="${col}"][row="${+row+1}"]`).getAttribute("color"));
qiAlex
  • 4,290
  • 2
  • 19
  • 35