Search code examples
c#csquery

CsQuery: how to iterate over all elements?


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?


Solution

  • 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')