jamietre / CsQuery

CsQuery is a complete CSS selector engine, HTML parser, and jQuery port for C# and .NET 4.
Other
1.16k stars 250 forks source link

Removing a script tag doesn't work if it's inside a div #158

Closed greg84 closed 10 years ago

greg84 commented 10 years ago

I'm trying to remove script tags from some markup, but it doesn't work if the script tag is inside another. When I run this:

var cq = CQ.Create("<div></div><script></script>");
cq.Remove("script");
return cq.Render();

The output is as expected:

<div></div>

However, when I change it to this:

var cq = CQ.Create("<div><script></script></div>");
cq.Remove("script");
return cq.Render();

It doesn't work, the output is the same as the original markup:

<div><script></script></div>

Am I doing something wrong or is this a bug?

jamietre commented 10 years ago

This is, perhaps counterintuitively, how it's supposed to work. The parameter for remove is a filter, so it only affects elements that are actually part of the selection. See: http://api.jquery.com/remove/#remove-selector

When you create a DOM using CQ.Create it returns a CQ object that has the top-level elements selected. So in the 1st example, cq has two members: a DIV element and a SCRIPT element. So the filter removes only the SCRIPT.

In the 2nd, only the DIV element is actually a member of cq; the SCRIPT is a child. So the filter will not match it.

An example using jQuery is here.

http://jsfiddle.net/jamietre/R3SBx/

greg84 commented 10 years ago

Makes perfect sense! Thanks for your help.

This is what I needed to do, which of course works fine:

var cq = CQ.Create("<div><script></script></div>");
cq.Find("script").Remove();
return cq.Render();