Skip to content
Advertisement

Extract value attribute from a HTML snippet

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>

Advertisement

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>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement