Home > Software design >  Extract Nested Tag Using PHP
Extract Nested Tag Using PHP

Time:05-13

Tag hierarchy in a webpage :

<body>
   <div id='header'>
      <h2>.....</h2>
   </div>
   <div id='main'>
      <h2>...</h2>
      //Some other content
      <h2>...</h2>
   </div>
   <div id='footer'>
      <h2>.....</h2>
   </div>
</body>

[PROBLEM : ] From the above hierarchy structure of a webpaege, I want to extract only the <h2> tags which are inside the <div id='main'>. Can someone please please help me out ?

What I have tried is.... using HTML DOM of php $h2Tags = $htmlDom->getElementsByTagName('h2');, but this gives me all the <h2> tag which are outside of main div as well. Please guide me to a solution.

CodePudding user response:

I have updated this to PHP:

h2_tags below will get list of h2s in main div:

$div_m = $htmlDom->getElementById('main');
$h2_tags = $div_m->getElementsByTagName('h2');

This is JS:

var div_m = document.getElementById("main");
var h2_tag = div_m.getElementsByTagName('h2');
  • Related