0

I'm just starting to code an extension and I've encountered a problem. I'm using "getElementById" to see if this is the correct webpage. And I'm always no matter what the same result "null". Can someone help me, please? Here is the code:

var abc = document.getElementById('questionText');
console.log(abc);
if (abc == null) {
    alert("not working");
} else {
    alert("works");
} 
morsznetik
  • 27
  • 3
  • 1
    What browser is this extension for? Which script is this code in (background, content, popup, etc.)? – Rojo Apr 18 '21 at 14:15
  • 1
    And when in the page lifecycle do you run this? Possibly related: https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – charlietfl Apr 18 '21 at 14:16

1 Answers1

1

Wrap the code inside DOMReady, otherwise you might end up looking for the element before HTML document has been completely loaded and parsed.

document.addEventListener('DOMContentLoaded', function() {
  var abc = document.getElementById('questionText');
  console.log(abc);
  if (abc == null) {
    alert("not working");
  } else {
    alert("works");
  }
});
naveen
  • 53,448
  • 46
  • 161
  • 251