Search code examples
c#htmldom-manipulationcsquery

Replace a DOM element with a different element using CsQuery


A have a HTML document containing a list of links:

  <div class="toc">
     <ul class="content_list">
        <li><a href="...">Chapter 1</a></li>
        <li><a href="...">Chapter 2</a></li>
        <li><a href="...">Chapter 3</a></li>

Is there a way (using CsQuery) to remove the anchor tags or to replace them with a different element (e.g. a <span>) while keeping the text?

The result should be either like this:

  <div class="toc">
     <ul class="content_list">
        <li>Chapter 1</li>

or like this:

  <div class="toc">
     <ul class="content_list">
        <li><span>Chapter 1</span></li>

Solution

  • var cq = new CsQuery.CQ(@"<div class=""toc""><ul class=""content_list"">
            <li><a href=""..."">Chapter 1</a></li>
            <li><a href=""..."">Chapter 2</a></li>
            <li><a href=""..."">Chapter 3</a></li>
    </ul></div>");
    
    cq[".toc > .content_list > li > a"]
        .Select(x => x.Cq())
        .ToList().ForEach(x => x.ReplaceWith(x.Text()));
        //or with a span wrapper
        //.ToList().ForEach(x => x.ReplaceWith(new CsQuery.CQ("<span/>").Text(x.Text())));
    
    cq.Html().Dump();
    

    This produce :

    <ul class="content_list">
        <li>Chapter 1</li>
        <li>Chapter 2</li>
        <li>Chapter 3</li>
    </ul>