Home > Software design >  An error while changing text with javascript
An error while changing text with javascript

Time:05-27

I'm using google recaptcha with my django project. But it is not English. So I want to change its writing with javascript.

html

{% extends 'base.html' %}
{% block content %}
<div >
    <div >
        <div >
            <div >
                <div >
                    <h1>Registration</h1>
                    <br><br>
                    <form  method="POST" novalidate>

                      {% csrf_token %}
                      {{form.as_p}}
                        <div >
                            <button id="submit" type="submit" >Register</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
  document.querySelector('#recaptcha-anchor-label').innerHTML = "I'm not a robot";

</script>

{% endblock %}

After I did that it won't apply the html in browser. Below the error message:

Cannot set properties of null (setting 'innerHTML')

(recaptcha-achor-label is an id)

CodePudding user response:

The problem is, that no element can be found by the following statement.

document.querySelector('recaptcha-anchor-label')

In case recaptcha-anchor-label is an id, you should use a # in front of it.

document.querySelector('#recaptcha-anchor-label')

see Document.querySelector()

CodePudding user response:

This problem should be caused by 'recaptcha-anchor-label', please check whether 'recaptcha-anchor-label' is “class” or “id”, if it is class, please add “.“ before it. If it is class, please add "#" before it.

eg:

document.querySelector('.recaptcha-anchor-label').innerHTML = "I'm not a robot";

or

document.querySelector('#recaptcha-anchor-label').innerHTML = "I'm not a robot";

CodePudding user response:

If you are still facing the error. So Try this out The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

So move the script tag after all the DOM elements i.e. at the bottom where body tag is ending.

Cannot set property 'innerHTML' of null

  • Related