Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
cómo obtener el atributo de un elemento secundario anidado

Quiero recuperar un valor de atributo específico desde el interior de los nodos secundarios anidados. ¿Cuál es la mejor manera de hacer esto?

El siguiente código funciona, pero no sabré la cantidad de nodos secundarios cada vez.

 parent.childNodes[0].childNodes[0].childNodes[0].getAttribute('placeholder');
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puedes resolver esto con una función recursiva.
Hice este para resolver el problema.

 function getNestedAttribute(node, attrib) { // this is not really eficient but I forced it to use childnodes if (node.childNodes.length && node.children.length) { node.childNodes.forEach((child) => { if (child.nodeName === "#text") return; return getNestedAttribute(child, attrib); }); } else { let attr = node.getAttribute(attrib) || null; if (!attr) return; console.log(`[${attrib}]`, attr, { info: { node, attrib, }, }); } }

Y aquí tienes una solución funcional =)

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Recursive Placeholder</title> </head> <body> <ul id="parent"> <li> <ul> <li><input type="text" placeholder="hi there" /></li> <li><input type="text" placeholder="hola" /></li> </ul> </li> </ul> <button type="button" onclick="getPlaceholder()">Get Placeholder</button> <div> <div> <div> <div> <button type="button" onclick="getAllTypes()">Get Types</button> </div> </div> </div> </div> <script> function getPlaceholder() { const parent = document.getElementById("parent"); getNestedAttribute(parent, "placeholder"); } function getNestedAttribute(node, attrib) { if (node.childNodes.length && node.children.length) { node.childNodes.forEach((child) => { if (child.nodeName === "#text") return; return getNestedAttribute(child, attrib); }); } else { let attr = node.getAttribute(attrib) || null; if (!attr) return; console.log(`[${attrib}]`, attr, { info: { node, attrib, }, }); } } // Extra: function getAllTypes() { getNestedAttribute(document.body, "type"); } </script> </body> </html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!