Search code examples
typescriptnodelist

Typescript How to iterate through Nodelist of html elements and get values?


I have Nodelist of inputs but don't know how to get values from it

let paragraphSubEl = document.querySelectorAll(
      '.add-article__form-subtitle'
    );

Solution

  • at first, you should set the type guard then iterate the whole HTML elements.

    If you don't do this. querySelectorAll return HTMLInputElement or null it's a type union, that's the reason typescript shows error. it's by default behavior the strict checker.

     let paragraphSubEl = document.querySelectorAll('.add-article__form-subtitle');
        if(paragraphSubEl) {
            paragraphSubEl.forEach(node =>  {   console.log(node.firstChild.nodeValue) })
        }