mulllhausen
mulllhausen

Reputation: 4435

set css style with php dom

i am looking at building my website with the php dom classes. supposing i already have a document with a body, if i add a div to the body like so:

$div = $document->createElement('div');
$document->getElementsByTagName('body')->item(0)->appendChild($div);

is there a way to set a 'style' attribute for this element which has multiple entries? eg one which ends up looking like this:

<div style="top: 40px; left: 60px;"></div>

i know i could do this:

$div->setAttribute('style', 'top: 40px; left: 60px;');

but i want each aspect of the style to be accessible without parsing the value through regex. this is because i would like to access the 40px value easily in other parts of my code.

Upvotes: 1

Views: 5295

Answers (3)

Ali Chegini
Ali Chegini

Reputation: 59

set a class for current element with setAttribute and add custom css to style.css file

Upvotes: -1

Gordon
Gordon

Reputation: 316939

XML Attributes are used to associate name-value pairs with elements. DOM does not (and cannot) know that you put CSS in there. That is because DOM is for arbitrary XML applications and not just for XHTML. CSS is a different Domain. So you have to parse it manually.

Alternatively, have a look at http://querypath.org. It supports adding and reading style attributes directly.

Upvotes: 3

Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

What about the structure (written by yourself) like this:

$div = new Div();
$div->addStyle('top:', '40px;');
$div->addStyle('left:', '60px;');
print_r($div->Style)//for access of all style elements in case you need to modify them
$document->addElement($div);
//in case you need to modify an already added element, just
$document->Elements[17]; //or something similar

Hopefully you will find something useful :)

Upvotes: 2

Related Questions