Skip to content
Advertisement

document.querySelectorAll(“body”) returning undefined

I am using the following codes in the console of the firefox DevTools to extract book names from https://bookauthority.org/books/best-problem-solving-books

Code 1

var selects=document.querySelectorAll("div.book-header-title a.book-title h2.main");

for (i = 0; i < selects.length; ++i) {
  console.log (selects[i].innerText);
}

Code 2

var selects=document.querySelectorAll("div.book-header-title a.book-title h2.main");
console.log(selects)

Even the following code is not working

var selects=document.querySelectorAll("body");
console.log(selects)

It only says undefined. What can I do?

Advertisement

Answer

querySelectorAll works just fine. The problem resides in that the specific webpage on which you’re executing the code, has overriden the window.console.log method and the new implementation apparently does not print arguments to the console, as its native implementation does.

You can see this by issuing window.console.log (without parentheses), which usualy prints something like ƒ log() { [native code] } (at least in Chrome).

There are hacks how to acquire the native implementation. See, for example, this post: https://stackoverflow.com/a/11129588/4005175


Example:

// restore window.console.log method
var f = document.createElement("iframe");
f.style.display = "none";
document.documentElement.appendChild(f);
window.console.log = f.contentWindow.console.log;

// print book titles
var selects=document.querySelectorAll("div.book-header-title a.book-title h2.main");
for (i = 0; i < selects.length; ++i) {
  console.log (selects[i].innerText);
}
8 People found this is helpful
Advertisement