To find and replace using querypath without destroying existing context you can use the following: 1 2 $temp = qp($output, 'table')->addclass('table'); $output = $temp->top('body')->innerHTML();