Search code examples
javascriptarraysdomselectors-api

query selecting alternating elements


I have the below HTML. I need to extract the text content into an array of maps like:

[{key: 'keyone', value: 'valone'}, {key: 'keytwo', value: 'valtwo'}, ... ]

The only way I can think is two extract all the element using document.querySelectorAll('ol *'); then to loop through each element and have some rule like if it is an odd number, add it as key with the following element as the value, then skip the next element. But this seems really hacky a brittle. Is there a better way to do this? Maybe using css selectors like :nth-last-of-type(2)?

<ol>
  <dt>keyone</dt>
  <dd>valone</dd>
  <dt>keytwo</dt>
  <dd>valtwo</dd>
  ...
</ol>

Solution

  • Assuming consistent pairs of dt-dd you could map the dt and use nextElementSibling to get the associated dd

    const dt = document.querySelectorAll( "ol dt" )
    
    const res = [...dt].map(el => {
      return {key: el.textContent, value: el.nextElementSibling.textContent}
    });
    
    console.log( res );
    <ol>
      <dt>keyone</dt>
      <dd>valone</dd>
      <dt>keytwo</dt>
      <dd>valtwo</dd>
    </ol>