Extract value attribute from a HTML snippet

Tags: ,



I’m trying to extract value property from a HTML file. I used querySelectorAll to get all the nodes in the file. Could anyone please help how do I only fetch value property from the file.

const nodes = document.querySelectorAll("add")
console.log(nodes)
<div>
  <add value="abc"></add>
  <add value="def"></add>
  <add value="ghi"></add>
</div>

Answer

Be sure to check that the selected nodes have the attribute value by adding [value] to the query.

Note: here i use the ES6 spread operator to get the NodeList as an array.

const nodes = document.querySelectorAll("add[value]")
console.log([...nodes].map(n => n.getAttribute("value")))
<div>
  <add value="abc"></add>
  <add value="def"></add>
  <add value="ghi"></add>
</div>


Source: stackoverflow