简体   繁体   中英

Can't assign querySelectorAll() to a variable - weird behaviour

I was trying to crawl a very old website for a specific tag, I need to get it by it's for= attribute. So I used this piece of code.

var character = document.querySelectorAll("label[for=char_1]");

For some reason it returns an undefined , but I was using this script for a few days now and it worked like a charm. Here's the fun part. Typing that command in browsers console will result in undefined . But typing this alone:

document.querySelectorAll("label[for=char_1]");

Will return a proper NodeList . Why it won't assign to a variable...?

edit: It seems that deleting var and typing character without it will make it work. It's resolved but I would still love to get an answer to "why is this happening"?

edit2:

for (var i = 0; i < 15; i++) {
    var character = document.querySelectorAll("label[for=char_" + i +"]");
    console.log(character); // this will return [] from the script.
    var color = character[0].children[0].style.color;
}

A simple for loop. All I get is Cannot read property 'children' of undefined . But I can type in the very same command document.querySelectorAll... and it will work in the browser and will return NodeList .

I had it working like this in a very hacky script. It worked.

var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;

edit3:

var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;

var character2 = document.querySelectorAll("label[for=char_2]");
var characterColor2 = character2[0].children[0].style.color;
// ...

The above code works without a single problem though. I don't think it's DOM not being ready as this code is also run from Greasemonkey script and it works. The only difference is the for loop.

var x = ""; // returns undefined, because it's a var assignment.
var elements = document.querySelectorAll('div');

That's expected behavior when pasted into the console.

edit: It seems that deleting var and typing character without it will make it work. It's resolved

I'm afraid you're creating a global scope variable now. or perhaps characters is an already defined variable in that scope.

Buhah, as I said in edit 3 "the only difference is the for loop". I was so busy trying to find an answer in the DOM-related things that I made the simplest mistake ever done in programming.

See?

char_1

With...

for(var i = 0...)

0! And I was testing char_1 in the browser instead of char_0. Which - truly - returns [] instead of something useful. Time to go on a holiday break I guess, my brain seems to be there already. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM