tags:

views:

27

answers:

2

Given the following html:

<ul id="search-results">
   <li>
        <h3>Result 1</h3>
        <span class="some-info">Tag line</span>
   </li>
   <li>
        <h3>Result 2</h3>
        <span class="some-info">Another bit</span>
   </li>
   <li>
        <h3>Result 2</h3>
        <span class="some-info">Another bit</span>
   </li>
</ul>

I can get the ul element with:

Element ul = ie.Element(Find.ById("search-results"));

How do I iterate over the children of the search-results?

I've managed to get as far as:

var allListItems = ie.Elements.Filter(e => e.Parent != null && e.Parent.Id == "search-results");

But this doesn't help me assert things about the H3 or span contained within the li's.

+2  A: 

Current best hack I can think of is:

public static class WatinExtensions
{
    public static ElementCollection Children(this Element self)
    {
        return self.DomContainer.Elements.Filter(e => self.Equals(e.Parent));
    }
}


ElementCollection results = ie.Element(Find.ById("search-results")).Children();

// and 

foreach(Element li in results)
{
    Element info = li.Children().First(e => e.ClassName.Contains("some-info"));
}

It works but surely there is a proper why to do this?

And there is a correct way to do this from the watin mailing list:

In my example:

var searchResults = (IElementContainer) ie.Element(Find.ById("search-results"));

foreach (Element element in searchResults.Elements) {
    // can do more here
}
Gareth Davis
+1  A: 

*Option1:*Based on your code, you can try something like:

ie.Spans.Filter(Find.ByClass("some-info"))[0...2].PreviousSibling;

you will need to loop over each span.

*Option2:*Based on some suggestions from the Watin mail list (similar to your own answer as well):

IElementContainer elem = (IElementContainer)ie.Element(Find.ById("search-results"));

Then you parse through elem.Element

Bolu
Thanks, this is pretty similar to my own answer... I just can't believe that an Element can't find it's own children
Gareth Davis
@Gareth: updated my answer, that's what we can get by far...
Bolu