如何使用JavaScript DOM API中的给定条件获取子节点? [英] How to fetch the child node with given criteria in javascript DOM api?

查看:106
本文介绍了如何使用JavaScript DOM API中的给定条件获取子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

xml文件如下:

<products>
  <product>
   <id>1</id>
   <name>pen</name>
  </product>
  <product>
   <id>2</id>
   <name>pencil</name>
  </product>
</products>
<employees>
  <employee>
   <name>Jack</name>
  <employee>
  <employee>
   <name>Mark</name>
  <employee>
</employees>

只能得到< name> < product> 的子节点的节点?在javascript dom中有很好的修改 xpath api

Can I only get the <name> nodes which are the childen of <product>? Is there well adapted xpath api in javascript dom?

推荐答案

在现代浏览器可以使用 querySelector 遍历xml树。假设你的xml位于 div#xmlsample 中,那么这个代码将给你一个nodeList,用于 // product / name prodNames

In modern browsers you could use querySelector to traverse the xml-tree. Let's say your xml resides within div#xmlsample, then this code will give you a nodeList for //product/name in prodNames:

var xmlDoc = (new DOMParser())
              .parseFromString(document.querySelector('#xmlsample').innerHTML,
              "application/xml"),
    prodNames = xmlDoc.querySelectorAll('product name');

请参阅这个jsfiddle

这篇关于如何使用JavaScript DOM API中的给定条件获取子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆