Skip to content

Instantly share code, notes, and snippets.

@miklb
Last active April 12, 2017 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miklb/2dff5a40a88c8d76e43b9d4e8771429c to your computer and use it in GitHub Desktop.
Save miklb/2dff5a40a88c8d76e43b9d4e8771429c to your computer and use it in GitHub Desktop.
attempting to get last a tag and apply a class
@miklb
Copy link
Author

miklb commented Apr 12, 2017

To re-iterate my comment on Twitter, this isn't mission critical work, just an itch I wanted to scratch, but at some point would like to understand why the if (end($links)) didn't work.

@norcross
Copy link

give this a try:

	// Set my DOM.
	$dom = new DOMDocument;
	$dom->loadHTML( $embed_html );

	// Set my XPath lookup.
	$xpath = new DOMXPath( $dom );
	$links = $xpath->evaluate( '//a' );

	// Bail if I don't have any links.
	if ( empty( $links->length ) || absint( $links->length ) < 1 ) {
		return;
	}

	// Get the count of my last link.
	$last  = absint( $links->length ) - 1;

	// Set my last item.
	$item = $links->item( $last );

	// Set the class on my last item.
	$item->setAttribute( 'class', 'u-url' );

	// Save the HTML back to the DOM.
	$html = $dom->saveHTML();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment