Joao Jesus
Joao Jesus

Reputation: 187

Using PHP to check if an Element(ID) has a specific class assigned

I want in my template.php (drupal theme) something like this:

$search_button ='search-button.png';
if($('#page-wrapper').hasClass('blue-colour')) {
    $search_button ='search-button-blue.png';
}
else if ($('#page-wrapper').hasClass('green-colour')) {
    $search_button ='search-button-green.png';
}
$form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/'.$search_button);

Which doesn't work because it is jQuery. The problem is the syntax on this bit:

if($('#page-wrapper').hasClass('blue-colour'))

How can I do the same thing without using javascript or jQuery and only php and/or some Drupal function?

I want to replace the icon for a search box based on a class set on a HTML element:

<div id="page-wrapper" class="blue-colour">

In this case it would check that the class is 'blue-colour' and would set the correct blue icon on the variable ($search_button).

Upvotes: 1

Views: 5259

Answers (3)

jeroen
jeroen

Reputation: 91734

This doesn't answer your question directly, but you can solve this very nicely using just css:

  1. Don't use an image for your button, but a text and do something like text-indent: -9999em;
  2. Set the background image of the button to the image you want like (simple example):

.blue-colour .button {
   background: url(search-button-blue.png);
}
.green-colour .button {
   background: url(search-button-green.png);
}

Upvotes: 2

Kristo J
Kristo J

Reputation: 631

You could try to use dom parser, though its going to be tricky.

http://simplehtmldom.sourceforge.net/manual.htm

Upvotes: 0

None
None

Reputation: 5649

javascript and jQuery are client-side, meaning the page is already loaded and javascript operates on the loaded DOM directly on the client's computer.

PHP is server-side, meaning the page is being written by PHP on the server and then the hypertext will be transferred to the client's computer.

Changing the image based on the class would require client-side code unless you already knew the class.

For example,

$class = 'blue-colour';
switch ($class) {
    case 'blue-colour':
        echo '<img src="blue-colour.jpg" alt="blue-colour" />'
        break;
    default:
        echo '<img src="default.jpg" alt="default" />';
}

How you determine the class is up to your code, but it has to be done during the parsing on the page.

Upvotes: 2

Related Questions