Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The DOM solution</p> <pre><code>$dom = new DOMDocument; $dom-&gt;loadHTML( $ul ); $xPath = new DOMXPath( $dom ); $xPath-&gt;query( '/html/body/ul/li[last()]/@class' ) -&gt;item( 0 ) -&gt;value .= ' myClass'; echo $dom-&gt;saveXml( $dom-&gt;getElementById( 'menu' ) ); </code></pre> <p>If you know the HTML to be valid, you can also use <code>loadXML</code> instead. That would make DOM not add ther HTML skeleton. Note that you have to change the XPath to <code>'/ul/li[last()]/@class'</code> then.</p> <p>In case you are not familiar with XPath queries, you can also use the regular DOM interface, e.g.</p> <pre><code>$dom = new DOMDocument; $dom-&gt;loadHTML( $ul ); $liElements = $dom-&gt;getElementsByTagName( 'li' ); $lastLi = $liElements-&gt;item( $liElements-&gt;length-1 ); $classes = $lastLi-&gt;getAttribute( 'class' ) . ' myClass'; $lastLi-&gt;setAttribute( 'class', $classes ); echo $dom-&gt;saveXml( $dom-&gt;getElementById( 'menu' ) ); </code></pre> <hr> <p><strong>EDIT</strong> Since you changed the question to have classes for first and last now, here is how to do that using XPath. This assumes your markup is valid XHTML. If not, switch back to <code>loadHTML</code> (see code above):</p> <pre><code>$dom = new DOMDocument; $dom-&gt;loadXML( $html ); $xpath = new DOMXPath( $dom ); $first = $xpath-&gt;query( '/ul/li[1]/@class' )-&gt;item( 0 ); $last = $xpath-&gt;query( '/ul/li[last()]/@class' )-&gt;item( 0 ); $last-&gt;value .= ' last'; $first-&gt;value .= ' first'; echo $dom-&gt;saveXML( $dom-&gt;documentElement ); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload