Error while running js

Asked

Viewed 55 times

0

I have the js code (below) to change the name of a link, but the script does not work. And when I do on the console works normally. Can anyone 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 mistake :

Uncaught Typeerror: Cannot 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>
  • Your selector is probably wrong. Try changing the selectorAll line to var x = document.querySelectorAll('.glis-thickbox .tb-added .qvBinded');

  • Put html in question too.

  • So it didn’t even work on the console.

  • @Lucashenrique No, with or without spaces are very different things. Without space the selector will look for the same element that has all classes informed. With space, the selector will be child elements, seeking class qvBinded within an element with the class tb-addedwithin an element with the class glis-thickbox.

  • @Gustavo, try to put your JS code inside the event onLoad HTML. So you will ensure that the JS runs only when the DOM is loaded.

1 answer

0

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

See playback of error 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 most appropriate is to wait for the loading of the document or the window itself, and then manipulate the DOM. And if you’re only interested in the first occurrence, it doesn’t make sense to go through the whole model like querySelectorAll() to access the first item, still not validate if any 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.