Error executing js

0

I have the js code (below) to change the name of a link, but the script does not work. And when I do the console it works normally. Can someone tell me what it would be? The script is at the end of the html document.

<script>
    var texto = "ADICIONAR";    
    var x = document.querySelectorAll('.glis-thickbox.tb-added.qvBinded');
    x[0].innerHTML = texto;
</script>

I have the following error:

  

Uncaught TypeError: Can not set property 'innerHTML' of undefined

HTML code:

<div class="insertsku-popup">
    <a id="6db09796a68f4625b293b54a7c6432e0" href="#" class="glis-thickbox tb-added qvBinded">
        Insert in my list
    </a>
</div>
    
asked by anonymous 09.11.2018 / 15:57

1 answer

0

This error happens because you are probably displaying the javascript block before you even display the element in html and expect it to be available in DOM , so var x is not defined and does not represent an object exposing the innerHtml attribute % that you try to access on the next line. The result is the error message displayed:

See the error message below:

<script>
    var texto = "ADICIONAR";    
    var x = document.querySelectorAll('.glis-thickbox.tb-added.qvBinded');
    x[0].innerHTML = texto;
</script>

<div class="insertsku-popup">
    <a id="6db09796a68f4625b293b54a7c6432e0" href="#" class="glis-thickbox tb-added qvBinded">
        Insert in my list
    </a>
</div>

To fix the problem:

You can simply add the javascript block to the end of the document, but the best you can do is wait for the document to load or the window itself, so you can manipulate DOM . And if you are only interested in the first occurrence, it does not make sense to go through the whole model as querySelectorAll() to access the first item, still without validating if one was found which would result in another different error.

window.onload = function(){
    var texto = "ADICIONAR";    
    var x = document.querySelector('.glis-thickbox.tb-added.qvBinded');
    
    if(x != null)
      x.innerHTML = texto;
}
<div class="insertsku-popup">
    <a id="6db09796a68f4625b293b54a7c6432e0" href="#" class="glis-thickbox tb-added qvBinded">
        Insert in my list
    </a>
</div>
    
19.11.2018 / 17:24