Search code examples
phpdomdocument

Target element within specific element domdocument


I want to target a tags with class genre within parent div with id test:

<div id="test">
   <a class="genre">hello</a>
   <a class="genre">hello2</a>
</div>

So far, I can get all the genre a tags:

$xpath = new DOMXPath($doc);
$elements = $xpath->query('//a[@class="genre"]');

... but I want to adjust //a[@class="genre"] so I only target the ones within the test div.


Solution

  • I don't understand why you did not write it yourself because you use all needed elements of xpath in your expression. Or, maybe, i've misunderstand you question

    $elements = $xpath->query('//div[@id="test"]/a[@class="genre"]');