开发者

Get the type of a given XML element with jQuery?

How can I figure out the type of a given XML element with jQuery?

For example, if I want the type of the second child:

XML:

开发者_如何学C
<xml>
  <a>a element</a>
  <b>b element</b>
  <c>c element</c>
</xml>

JS:

var node = $(xml).eq(2);
var nodeType = getNodeType(node);
if (nodeType == 'b') {
   alert('GOT IT');
}


function getNodeType($node) {
   ...
} 


Try using nodeName on the element (not on the jQuery object).

Example: http://jsfiddle.net/2cSpq/

var xml = "<xml><a>a element</a><b>b element</b><c>c element</c></xml>";

var node = $(xml).children().eq(1);
var nodeType = alert(getNodeType(node));
if (nodeType == 'b') {
   alert('GOT IT');
}


function getNodeType($node) {
   return $node[0].nodeName.toLowerCase();  <--- right here
} 

I also used the children()[docs] method to target the nested elements, which would make the b element at index 1, not 2.

The [0] extracts the node from the jQuery object, .nodeName gets the node's name, and .toLowerCase() ensures it is sent to you as the lower case letter you're testing for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜