document.querySelector always returns null

前端 未结 4 1730
野的像风
野的像风 2021-01-20 01:38

I\'ve looked at the other answers but still don\'t understand.

For some reason this line of code always returns null.

var els = document.querySelecto         


        
相关标签:
4条回答
  • 2021-01-20 01:58

    I doubt your JS gets loaded before the markup and css. In that case, you could try using <script src="" defer></script>

    The contents are loaded first and your java script should work fine after that.

    0 讨论(0)
  • 2021-01-20 02:10

    I don't know your full javascript code but maybe you are create/append that element after the script loads or something like that and therefor querySelector don't find the element with that id. Check your scope or write the code here if you suspicious of that kind of error.

    0 讨论(0)
  • 2021-01-20 02:12

    Possible solutions to your problem...

    IIFE

    (function () {
      var els = document.querySelector("[id='MTG_INSTR$2']");
      console.log(els);
    })();
    

    DOMContentLoaded

    document.addEventListener("DOMContentLoaded", function () {
      var els = document.querySelector("[id='MTG_INSTR$2']");
      console.log(els);
    });
    
    0 讨论(0)
  • 2021-01-20 02:22

    IDs are handled specially in CSS selector syntax, with a # followed by the ID, so you'd normally want something like document.querySelector('#MTG_INSTR$2'), but $ isn't a legal ID component, so ideally you'd give it a better name. Other approaches are:

    document.getElementById('MTG_INSTR$2'); // No need to change ID
    

    That said, on testing, document.querySelector("[id='MTG_INSTR$2']") should work, so you might check if anything actually has that ID on your page.

    0 讨论(0)
提交回复
热议问题