Reputation: 88
I tried to parse the color-names on this page: http://www.google.com/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?
Upvotes: 4
Views: 4504
Reputation: 173522
If 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.
Upvotes: 7
Reputation: 198294
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.
Upvotes: 3