Search code examples
javascriptarraysnode.jsdomdomdocument

I'm creating an array of DOM elems and am selecting a img tag, then a series of p tags, how can I get innerHTML of the p's and src link from the img?


This is how I'm creating the array: const textData = Array.from(document.querySelectorAll('.product-image, .product-detail > p'))

The array contents are an img tag followed by a amount of p tags and depending on how many items are on the page, more img tags followed by more p tags, I would like to map or loop through the elements and based on what tag the element is, replace it in the array with its innerHTML(for the p tag) or its src link(img tag). How can I achieve this in node? I cant figure out how to loop through and determine the tag type and preform the specified operation.


Solution

  • You could use a map and tagNAme

    textData.map((element) => {
      if (element.tagName === 'IMG') return element.src;
      if (element.tagName === 'P') return element.innerHTML;
      return '';
    })