I'm trying to grab an xml node by its attribute.
edit
I'm trying to retrieve an element by its attribute value using javascript xml instead of jquery. Is there a simple method for this?
I'm trying to grab an xml node by its attribute.
edit
I'm trying to retrieve an element by its attribute value using javascript xml instead of jquery. Is there a simple method for this?
Share Improve this question edited Oct 5, 2015 at 22:33 temporary_user_name 37.1k48 gold badges160 silver badges243 bronze badges asked Aug 16, 2011 at 18:44 WennWenn 3492 gold badges4 silver badges14 bronze badges 5 |4 Answers
Reset to default 5It is really easy using jQuery. Suppose we have a string like this.
<document>
<value type="people">
<name>
John
</name>
</value>
<value type="vehicle">
<name>
Ford
</name>
</value>
</document>
Then
var xmlDocument = $.parseXML(str);
$(xmlDocument).find("value[type='people'] name").text()
We will get string 'John' back.
You have to find a list of elements first, then filter by their attributes.
Check out my demo here: http://jsfiddle.net/silkster/eDP5V/
I feel this justifies a new answer as it is JQuery Free
document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName((tagName || '*'));
return $A(children).inject([], function(elements, child) {
var attributeValue = child.getAttribute(attribute);
if(attributeValue != null) {
if(!value || attributeValue == value) {
elements.push(child);
}
}
return elements;
});
}
source
it has been pointed out to me that I posted the wrong script.. hehe read here
// document.getElementsByAttribute([string attributeName],[string attributeValue],[boolean isCommaHyphenOrSpaceSeparatedList:false])
document.getElementsByAttribute=function(attrN,attrV,multi){
attrV=attrV.replace(/\|/g,'\\|').replace(/\[/g,'\\[').replace(/\(/g,'\\(').replace(/\+/g,'\\+').replace(/\./g,'\\.').replace(/\*/g,'\\*').replace(/\?/g,'\\?').replace(/\//g,'\\/');
var
multi=typeof multi!='undefined'?
multi:
false,
cIterate=document.getElementsByTagName('*'),
aResponse=[],
attr,
re=new RegExp(multi?'\\b'+attrV+'\\b':'^'+attrV+'$'),
i=0,
elm;
while((elm=cIterate.item(i++))){
attr=elm.getAttributeNode(attrN);
if(attr &&
attr.specified &&
re.test(attr.value)
)
aResponse.push(elm);
}
return aResponse;
}
jquery can do this very easily. http://think2loud.com/224-reading-xml-with-jquery/
DomParser
orloadXML
in the case of IE: w3schools.com/Xml/xml_parser.asp But seriously, use jQuery. – Alex Churchill Commented Aug 16, 2011 at 19:04