0

I need to implement a function that returns the first element the has Id attribute that contains a certain string.

in HAP I used to implement it as follows:

    protected HtmlNode GetElementByIdPattern(string pattern)
    {
        return doc
            .DocumentNode
            .Descendants()
            .FirstOrDefault(e => e.Attributes["id"] != null && e.Attributes["id"].Value.Contains(pattern));
    }

How do I loop over all elements in CsQuery?

Nizar Blond
  • 1,826
  • 5
  • 20
  • 42
  • You're using an operator that specifically grabs a single result. There is only one result. If you want *all* of the results, then don't use an operator that just grabs a single result... – Servy Jan 03 '14 at 18:15
  • which operator are you talking about? this is HAP don't mind it. I need the equivalent of .Descendants() – Nizar Blond Jan 03 '14 at 18:27

2 Answers2

2

The solution is:

    protected static CQ GetElementByIdPattern(CQ doc, string contains)
    {
        string select = string.Format("*[id*={0}]", contains);
        return doc.Select(select).First();
    }

Based on the jQuery syntax: $('[id=contains]: first')

Nizar Blond
  • 1,826
  • 5
  • 20
  • 42
0
 function CQ test(string contains, string selector)
 {
    CsQuery.CQ page="<div id="test first"></div>";
    return page[selector+"[id*="+contains+"]:first"];
 }

It's will return a CQ object you can manipulate with it as you want.

nazarkin659
  • 503
  • 3
  • 11