0

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>

3
  • From the file or from the element? Your context is not clear. There are multiple value attributes. Are you looping? Show your code. Commented Sep 25, 2020 at 21:37
  • You do realize that <add> is not valid HTML? Commented Sep 25, 2020 at 21:39
  • The add part was some part of xml file. For data extracting purpose, I have added it to a HTML file. @EmielZuurbier Commented Sep 25, 2020 at 21:45

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

You can use Array.prototype.map with Array.from:

const nodes = Array.from(document.querySelectorAll("add")).map(el => el.getAttribute('value'))
console.log(nodes)
<div>
  <add value="abc"></add>
  <add value="def"></add>
  <add value="ghi"></add>
</div>

Comments

2

You can map over the node collection, and call getAttribute() on each:

const nodes = document.querySelectorAll('add');

const values = Array.from(nodes).map(node => node.getAttribute('value'));

console.log(values);
<div>
  <add value="abc"></add>
  <add value="def"></add>
  <add value="ghi"></add>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.