Search code examples
javascriptdomparser

jsdom how to get an element inside another element inside foreach


i am new to JSDOM parser.

I have the following:

<div id='mydiv'>
  <ul>
    <li><a title='a'>TextA</a></li>
    <li><a title='b'>TextB</a></li>
    <li><a title='c'>TextC</a></li>
    <li><a title='d'>TextD</a></li>
  </ul>
</div>

I am using the following code but not able to get the text 'TextA', 'TextB', 'TextC', 'TextD'

const categoryDiv = dom.window.document.querySelectorAll('#mydiv > ul > li')
  .forEach(item => {
    console.log('item', item.getElement('a')); //not sure how to continue from here
  });
})

Solution

  • This could be as simple as:

      let targets = document.querySelectorAll('#mydiv > ul > li a');
    
      for (let target of targets) {
        console.log(target.text); 
      }