1

I'm trying to retrieve the onclick value on a td element. This is what I have so far.

$xpath = new DOMXPath($dom);
$trs = $xpath->query("/html/body//table/tr");


foreach ($trs as $tr){
    $tds = $xpath->query("td", $tr);
    foreach ($tds as $td) {
        $a = $xpath->query("@onclick", $td);
        echo $a->nodeValue;
        echo $td->nodeValue;
    }
}

This doesn't seem to be working though.

Here's the structure

<table>
   <tr>
       <td>Name</td>
       <td onclick="blahblah">Author</td>
       <td>Title</td>
   </tr>
</table>
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
kylex
  • 14,178
  • 33
  • 114
  • 175
  • 1
    why dont you fetch the attributes directly, e.g. `/html/body//table/tr/td/@onclick`? – Gordon Sep 01 '12 at 21:24
  • Because I also need the td nodeValue – kylex Sep 01 '12 at 21:27
  • well, but still, why dont you fetch all the tds then? why fetch the tr elements first? `/html/body//table/tr/td[@onclick]` would give you all the tds with an onclick attribute. – Gordon Sep 01 '12 at 21:29
  • Because I also need the other td node values which do not have an onclick attribute. So I collect 3 td nodevalues, but in addition need the onclick attribute for one of the td elements. – kylex Sep 01 '12 at 21:30
  • ok, but that doesnt explain why you are fetching the tr elements and then query the td elements from the tr elements when you can simply fetch all the td elements and iterate those and use getAttribute on them to check whether they have an onclick attribute. On a sidenote "doesnt seem to be working" is not a sufficient error description. What is not working. – Gordon Sep 01 '12 at 21:32
  • @Gordon, it is situated the way it is because of the way I need to gather the information. If I loop over all tds, I have no way of determining what section it is in. It's not working because I am not seeing a value for `$a->nodeValue` – kylex Sep 01 '12 at 21:35
  • 2
    how about http://codepad.org/sjxHqCVk? If you need to get to a TR from any of the TDs you can simply call `parentNode`. I guess that would give you your section information (cant tell because there is such thing in your example) – Gordon Sep 01 '12 at 21:36
  • Ha, the hasAttribute works beautifully! If you want to add this as an answer I will make sure to select it as the correct solution. – kylex Sep 01 '12 at 21:39
  • Hmm, it's basically the same as my answer to [this](http://stackoverflow.com/questions/3820666/grabbing-the-href-attribute-of-an-a-element/3820783#3820783). – Gordon Sep 01 '12 at 21:41

1 Answers1

0

$a is a NodeList, you must select an item:

 @print($a->item(0)->nodeValue);
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201