Search code examples
phpjavascripthtmlxquerydomxpath

DOMXPath->query(???) to search every node in an HTML document looking for JavaScript


How would one search through a HTML document to find the JavaScript myfunc within it? That is, I'd like to find the aforementioned needle in an HTML haystack that may contain the following nodes.

  • <p onMouseOver="myfunc(a,b,c)">blah blah blah</p>
  • <a href="javascript:MyFunc(a, b, c)">blah blah blah</a>
  • <img onmouseover='myFunc(a,b, c )' src="someimage.gif">

The PHP code I am currently using is:

foreach($domxpath->query('[onmouseover^="myfunc"]') as $node) {
    $text = $node->nodeValue;
    echo "<br>text=".$text;  // just to see what i get
}

Solution

  • You're not just searching for onmouseover it seems (look at the <a>). Hopefully the function name is consistent because PHP is only XPath 1.0

    //*[@*[contains(.,"myfunc")]]
    

    This selects any node anywhere with any attribute that contains "myfunc" (case sensitive).