Reputation: 10547
Say I have xml like this:
<outer>
<inner name="name0" type="type0" />
<inner name="name1" type="type1" />
<inner name="name2" type="type2" />
</outer>
I'm parsing the xml using jquery and I'm inside the each loop of the outer tag:
$(xml).find('outer').each(function() {
//what goes here?
});
Say I know the values that can appear in the name id of <inner>
. How do I, in the code above, get the appropriate type from the given <inner>
tag.
Example:
I have the string var name = "name1"
Inside the each loop, I need to pull type1
from the <inner>
tag that has name="name1". Thanks
Upvotes: 1
Views: 423
Reputation: 536469
I'm parsing the xml using jquery
Not really. $()
does not include an XML parser; you are parsing it as HTML, using the browser's innerHTML
parser. Because your input is not valid HTML, you might get any old strange DOM as the output, especially in IE, which doesn't like custom elements much.
It's annoyingly tricky to get an XML parser in a cross-browser way; it is much less well-supported than having XMLHttpRequest
return an XML document. In many modern browsers you can ask for a new DOMParser
, but for IE you have to create an MSXML2.DOMDocument
ActiveXObject, and for a few older browser you have to document.implementation.createDocument
(and even then the load
method isn't standard or supported everywhere).
Upvotes: 3
Reputation: 15221
var name = "name1";
$(xml).find('outer').each(function() {
var type = $(this).children('[name=' + name + ']').attr('type');
});
Upvotes: 0
Reputation: 630469
You can use an attribute-equals selector, like this:
var name="name1";
$(xml).find('outer').each(function() {
var type = $(this).children("[name='" + name + "']").attr("type");
//use type
});
You can give it a try here, if the XML is exactly what you posted and not a subset, just remove the .find('outer')
, since the root element is already where you want to be.
Upvotes: 0