skip to Main Content

I’m trying to find the value of elements that are generated by code.

This makes the elements:

let numNotifs = 1;

// this below is inside a loop
addFill = `<br><input type = 'number' id = 'notif${numNotifs}'>';
++numNotifs;

And I try to find them using this:

let i = 1;
while (i < numNotifs + 1) {
  save(parseInt(document.querySelector(`#notif${i}`).value));
  ++i;
}

However it gives me Uncaught TypeError: document.querySelector(...) is null
even though this exists in the html file.

<input type="number" id="notif1" min="1" max="60">

How should I fix this?

2

Answers


  1. I made sample code as per your description. If it works for you and you need more information on how it works I will write a more detailed description.

    Example:

    let numNotifs = 1;
    
    document.addEventListener('DOMContentLoaded', function () {
    
        let notificationInputsContainer = document.getElementById('notificationInputs');
    
        // Add the initial input
        addNotificationInput();
    
        function addNotificationInput() {
            let inputElement = document.createElement('input');
            inputElement.type = 'number';
            inputElement.id = `notif${numNotifs}`;
            inputElement.min = '1';
            inputElement.max = '60';
    
            notificationInputsContainer.appendChild(inputElement);
            numNotifs++;
        }
    
        // Add more inputs (for demonstration purposes)
        for (let i = 0; i < 3; i++) {
            addNotificationInput();
        }
    });
    
    document.querySelector('.myButton')
        .addEventListener('click', function () {
    
            // Find and save the values of the notification inputs
            let i = 1;
            while (i < numNotifs) {
                let input = document.querySelector(`#notif${i}`);
                if (input) {
                    save(parseInt(input.value));
                }
                i++;
            }
    
            function save(value) {
                console.log('Value:', value);
            }
    
        });
    <div id="notificationInputs">
    </div>
    
    <input type="button" value="Click me" class="myButton">
    Login or Signup to reply.
  2. Viewing your code led me this conclusion that you want to create some elements through loops and then want to access those !

    Here’s an exmaple also note instead of changing the innerHTML which is pre assumable since you’re writing some html string and it is not what you want to consider, you must create elements using Javascript.

    <div id="inputs"></div>
    
    <script defer>
          const numNotifs = 10;
    
          const elementToAppendChilds = document.querySelector("#inputs");
    
          // Creating inputs through loop and appending them
          for (const x of Array(numNotifs)) {
            // creating a wrapper to wrap the element
            const wrapperDiv = document.createElement("div");
            wrapperDiv.classList.add("wrapper");
            const inputEl = document.createElement("input");
            inputEl.id = `notif${x}`;
            wrapperDiv.appendChild(inputEl);
    
            elementToAppendChilds.appendChild(wrapperDiv);
          }
    
          const elements =
            elementToAppendChilds.querySelectorAll("input[id^='notif']");
          elements.forEach((element) => {
            // call custom function instead of logging value to console
            console.log(parseInt(element.value));
          });
    </script>
    

    Note I used defer attribute in script tag which ensures that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. ( no need to listen to dom load event )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search