Home > front end >  Typescript How to iterate through Nodelist of html elements and get values?
Typescript How to iterate through Nodelist of html elements and get values?

Time:11-01

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

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

CodePudding user response:

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) })
    }
      
  • Related