T110
T110

Reputation: 67

How do I access DOM elements on a php page with php?

I want to run this code in my header.php file

<?php 
$doc = new DOMDocument();
$doc->load('wp-content/themes/foo/header.php');
$header_li_elements = $doc->getElementsByTagName('li');
foreach($header_li_elements as $value){
echo $value->nodeValue;
}
?>

is this possible?

I want to be able to run a php function that checks what page I'm currently on, and then changes the id attribute of the particular nav element so that I can dynamically change the look of the nav element for whatever page I'm on.

Currently I'm just trying to get access to the 'li' elements on the page that I'm on and then echo them, I can work from there. Any thoughts?

Sorry if it's confusing. Kind of hard for me to describe what I'm thinking.

Upvotes: 0

Views: 749

Answers (2)

shovemedia
shovemedia

Reputation: 191

To do this, your php is going to have to parse your HTML as though it were XML. Not impossible, but a job much better suited to a one-line jQuery.

If you insist on doing this server-side for whatever reason, it'd be much better to catch the list items as they're being generated, rather than waiting until they're returned as one giant string and then trying to turn them all back into tags so you can manipulate them only to turn them back into one giant string again.

Looks like Wordpress, and I'm pretty sure Wordpress has API available to help you accomplish this, but we'd need to see exactly what's going on in that header.php.

Upvotes: 0

John Conde
John Conde

Reputation: 219934

Since that page is dynamic (e.g. the HTML is produced by PHP) this won't work because the HTML you wish to parse won't exist yet. It isn't created until runtime. You'll have to find an alternative way to do this such as checking what the current URL is and using that to determine how the navbar should look.

Upvotes: 4

Related Questions