Search code examples
jquerycsquery

Create new CsQuery object without inheritance


directly to the question:

I have CsQuery object with some data.

 CQ html=new CQ("<div id='wrapper'> <p id='getIt'></p> </div>");

I want to get p and assign it to a new CQ object :

 Cq newHtml=html["p"];

When I do that, it also inherits the original DIV. How can I make p element be the 'root'. ?

I have been trying everything:

after html.MakeRoot() if I use .Select() it still returns the DIV.

Also I tried using the .Find function (it search within the selected element) but it doesn't resolve my problem because I use a third-party library function which uses .Select()...

I know that I can do something like that

    CQ html=new CQ(html["p"].RenderSelection());

But it's kind of....

Thank you!


Solution

  • First of all, I humbly suggest the new 1.3 creation syntax over the old one:

    CQ html=CQ.CreateFragment("<div id='wrapper'> <p id='getIt'></p> </div>");
    

    Now, like you wanted, we want to get the inner p element, then create a new DOM context, we can do this by invoking the constructing method again. I think code will be easier :)

     CQ html = CQ.CreateFragment("<div id='wrapper'> <p id='getIt'>Hello</p> </div>");
     //Create a _new_ context
     CQ newHtml=CQ.CreateFragment(html["p"]);
     newHtml.Text("World");
     Console.WriteLine("{0} {1}",html["p"].Text(),newHtml.Text());//Hello World
     Console.Read();
    

    If you have any more questions, feel free to let me know.