1

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.

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ah right. this rules out doing it natively with the php dom classes then. cheers
2

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 :)

1 Comment

that looks like a nice clean way of doing it! i'm still a bit new to the php dom classes - how would i code my Div class to make sure that when i do the $document->addElement($div); it will not crash?
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.