I tried to parse the color-names on this page: .html#
Using this code:
var all = document.querySelectorAll(".color-group");
for(var i=0; i<all.length; i++){
var e = all[i];
var name = e.querySelector('span.name');
console.debug(name.innerHTML);
}
However the printed result is always undefined
.
This slightly changed code however works:
var all = document.querySelectorAll(".color-group");
for(var i=0; i<all.length; i++){
var e = all[i];
var name = e.querySelector('span.name').innerHTML;
console.debug(name);
}
The only difference is that I access the result of querySelector
directly and not via the name
-variable.
I tried it with Chrome, Safari and Firefox which all did not return the color-names. IE however manged to get it right this time.
Is this a general bug or feature or is it a problem with the website?
I tried to parse the color-names on this page: http://www.google./design/spec/style/color.html#
Using this code:
var all = document.querySelectorAll(".color-group");
for(var i=0; i<all.length; i++){
var e = all[i];
var name = e.querySelector('span.name');
console.debug(name.innerHTML);
}
However the printed result is always undefined
.
This slightly changed code however works:
var all = document.querySelectorAll(".color-group");
for(var i=0; i<all.length; i++){
var e = all[i];
var name = e.querySelector('span.name').innerHTML;
console.debug(name);
}
The only difference is that I access the result of querySelector
directly and not via the name
-variable.
I tried it with Chrome, Safari and Firefox which all did not return the color-names. IE however manged to get it right this time.
Is this a general bug or feature or is it a problem with the website?
Share Improve this question edited Dec 9, 2014 at 4:56 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Dec 9, 2014 at 4:44 jahebajaheba 881 silver badge6 bronze badges 02 Answers
Reset to default 7If you're running that code in the global scope, the variable name
conflicts with that of window.name
(which is a string); consider creating a scope:
(function() {
var all = document.querySelectorAll(".color-group");
for(var i=0; i<all.length; i++){
var e = all[i];
var name = e.querySelector('span.name');
console.debug(name.innerHTML);
}
}());
Or, just run that code inside a regular named function and call that from the global scope.
It seems there is something special about variable name
.
var name = 3; name
// => "3"
var dame = 3; dame
// => 3
This behaviour is exhibited even by a blank tab (in Chrome at least). If you name your variable something else, it will go away. I believe (!) the reason is that you're executing in console, and name
always refers to window.name
; it goes away if you run it in a script; but I am not 100% sure my explanation is the correct one.