javascriptvariables

Variable doesn't work


For some strange reason the code below doesn't work.

var xxx = localStorage.getItem('position');
var foo = document.querySelectorAll("div[current_position=' + xxx + ']");
for (var i = 0; i < foo.length; i++)
{
    // ...
}

Some facts:

  1. The localStrorage work correct - localStorage.getItem('position') outputs the correct value. No error here.

  2. current_position is a number (1, 2, 3, ... etc). If I manually set, for example, '2', like below:

    var foo = document.querySelectorAll("div[current_position='2']");
    

    then the code work as it should. But if I change '2' to a ' + xxx + ', it doesn't work.

Original question was edited. Thanks to Bhojendra Nepal and Jonah Williams.


Solution

  • Ok, I found the solution myself. The second line of the code should be:

    var foo = document.querySelectorAll("div[current_position='" +xxx+ "']");
    

    And all works.