Entry
How can I apply a condition to filter out certain elements in a child node or descendant accessor?
How can I apply a condition to filter out certain elements in a child node or descendant accessor?
Apr 5th, 2005 03:10
Martin Honnen,
You can apply an XML filtering predicate operator to an XML object or an
XMLList object using the following syntax
xml(List)Object.(filtering predicate expression)
The filter predicate expression is applied with each object being added
to the scope chain and an XMLList object with all object for which the
filtering predicate expression yields true is returned.
The following examples make that clearer, we have the following XML:
var html = <html>
<head>
<title>Example markup</title>
<style type="text/css">
.class1 { }
.class2 { }
</style>
</head>
<body>
<h1 class="class1">Example markup</h1>
<div class="class2">
<p id="p1" class="class1">Kibology for all.</p>
</div>
<p class="class1 class2">All for Kibology.</p>
</body>
</html>;
To find the <p> element with id attribute value 'p1' you can use a
descendant accessor with a filtering predicate as follows:
var p1 = html..p.(@id == 'p1');
alert(p1); // shows 'Kibology for all.'
alert(p1.toXMLString());
// shows '<p id="p1" class="class1">Kibology for all.</p>'
The expression html..p selects all <p> descendants and the filtering
predicate expression .(@id == 'p1') filters out exactly the one <p>
element with the id attribute value being 'p1'.
To find all elements for which the class attribute is exactly 'class1'
you can use a descendant accessor with a filtering predicate as follows:
var elementList = html..*.(@class == 'class1');
alert(elementList.length()); // shows 2
If you want to access all elements for which the class attribute
contains the value 'class2' you need a more complex predicate but as the
predicate can be any kind of JavaScript expression you can for instance
use regular expression matching:
var elementList = html..*.(/(^|\s+)class1(\s+|$)/.test(@class));
alert(elementList.length()); // shows 3
alert(elementList);
/* shows
'<h1 class="class1">Example markup</h1>
<p id="p1" class="class1">Kibology for all.</p>
<p class="class1 class2">All for Kibology.</p>'
*/