Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector returns String instead of DOM-Element

Tags:

javascript

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?

like image 855
jaheba Avatar asked Dec 26 '22 01:12

jaheba


1 Answers

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.

like image 56
Ja͢ck Avatar answered Jan 06 '23 01:01

Ja͢ck