Search code examples
phpjqueryphpquery

How to chain in phpquery (almost everything can be a chain)


Good day everyone, I'm very new with phpquery and this is my first post here at stackoverflow for a reason that i cant find the correct for syntax for the phpquery chaining. I know someone knows what i been looking for.

I only want to remove the a certain div inside a div.

 <div id = "content"> 
        <p>The text that i want to display</p>
        <div class="node-links">Stuff i want to remove</div>
 </content>

This few lines of codes works perfect

 pq('div.node-links')->remove();
 $text = pq('div#content');
 print $text; //output: The text that i want to display

But when I tried

$text = pq('div#content')->removeClass('div.node-links'); //or
$text = pq('div#content')->remove('div.node-links');

 //output: The text that i want to display (+) Stuff i want to remove

Can someone tell me why the second block of code is not working?

Thanks!


Solution

  • The first line of code will only work if your trying to remove the class from div.node-links, it won't remove the node.

    If you are trying to remove the class you need to change it from:

    $text = pq('div#content')->removeClass('div.node-links');
    // to
    $text = pq('div#content')->find('.node-links')->removeClass('node-links')->end();
    

    which will output:

    <div id="content">
        <p>The text that i want to display</p>
        <div>Stuff i want to remove</div>
    </div>
    

    As for the second line of code.. I'm not exactly sure why it is not working, it seems like your not selecting .node-links but I was able to get the desired results using these.

    // $markup = file_get_contents('test.html');
    // $doc = phpQuery::newDocumentHTML($markup);
    $text = $doc->find('div#content')->children()->remove('.node-links')->end();
    
    // or 
    
    $text = pq('div#content')->find('.node-links')->remove()->end();
    
    // or 
    
    $text = pq('div#content > *')->remove('.node-links')->parent();
    

    Hope that helps