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>
Your selector is probably wrong. Try changing the selectorAll line to
var x = document.querySelectorAll('.glis-thickbox .tb-added .qvBinded');
– Lucas Henrique
Put html in question too.
– Lucas Henrique
So it didn’t even work on the console.
– Gustavo
@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 classtb-added
within an element with the classglis-thickbox
.– Woss
@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.– Woss