使用 querySelectorAll,如何在某些情况下捕获属性,在其他情况下如何捕获整个元素?

Using querySelectorAll, how can I catch the attributes in some cases and the whole element in other cases?

使用节点并有类似的东西:

const carsforsale = Array.from(document.querySelectorAll(div > p, div > a, div> div > h1))
return carsforsale.map(elem => elem.innerText)

假设我想从 <p><h1> 中捕获 innerText 而不是从 <a> 中捕获,因为我只想从 <a> 和 innerText 中捕获 href 属性当使用 map 函数时也会返回,用不必要的信息填充数组。

有没有简单的方法可以在查询选择器函数上执行此操作?

或者甚至是在地图功能上执行此操作的简单方法?

请注意 Array.from 接受第二个参数,它是一个映射器函数 - 只要你有一个 Array.from 后跟一个 .map,你可以将它压缩成一个 Array.from.

在映射器函数中,您只需要检查要迭代的元素的 tagName

return Array.from(
  document.querySelectorAll('div > p, div > a, div> div > h1'),
  elem => (
    elem.tagName === 'A' ? elem.href : elem.innerText
  )
);

另请注意,当您使用字符串时,它们需要用分隔符括起来,例如 '"`。 (document.querySelectorAll(div > p, div > a, div> div > h1) 将导致 SyntaxError

旁注,您可能想要textContent而不是innerText。在大多数情况下,innerTexttextContentquirky, harder to use 版本。