Uncaught TypeError: Cannot read properties of undefined getElementById

Viewed 31

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 class="optionRow">
                    <label for="option1"> <input class="option" 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 ?

3 Answers

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;

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.

Related