Home > front end >  Uncaught TypeError: Cannot read properties of undefined getElementById
Uncaught TypeError: Cannot read properties of undefined getElementById

Time:09-22

i want get element by id but if i'm using the getElementById and passing the correct id so im getting the error of "Uncaught TypeError: Cannot read properties of undefined (reading 'getElementById')"

  1. List item html

    enter code here:

 <div >
                    <label for="option1"> <input  type="radio" value="a" id="option1" name="option">
                        Option 1 </label>
                </div>
enter code here :

javascript

 allOptions[1].document.getElementById('option1').innerHTML = data.a;
    allOptions[2].document.getElementById('option2').innerHTML = data.b;
    allOptions[3].document.getElementById('option3').innerHTML = data.c;

to ask why this error ?

CodePudding user response:

to ask why this error ?

Only the document object offers the function getElementById. id must be unique and therefore there is no need for a HTMLElement version of it.

Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll(), getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.

So in your case the correct usage of getElementById would be:

document.getElementById('option1').innerHTML = data.a;

Yet be aware that input does not support innerHTML. If you want to change the value take:

document.getElementById('option1').value= data.a;

CodePudding user response:

Just change allOptions[1].document.getElementById('option1') to document.getElementById('option1')

Because the document object is the root node of the HTML document. You can call document or window.document, not from element.

CodePudding user response:

Try

document.getElementById('option1').innerHTML = data.a;

The document is the a huge container, holding many informations about the site. Check out this website: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById for more information. In it is also a link to the document element.

Greetings!

  • Related