Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

#7 Ability to add new DOM elements ?

open
S. C. Chen
None
5
2012-10-10
2008-06-22
Anonymous
No

I know the class is able to manipulate DOM elements' attributes, removing DOM elements and dump back the DOM tree into HTML but can you add the ability to add new DOM elements to the tree ? Thanks.

Discussion

  • S. C. Chen
    S. C. Chen
    2008-06-24

    Logged In: YES
    user_id=2013304
    Originator: NO

    Thanks for your advice, I really think that:

    $e->outertext = 'foo' . $e->outertext;

    is more easy than:

    $n = new Element();
    $n->tag = 'b';
    $n->innertext = 'foo';
    $e->insertBefore($n);

    But I will keep this issue open to remind me to find a better way.

     
  • Logged In: NO

    I think that ( this is the way that most Javascript frameworks use ) :

    $attributes = array(
    'method' => 'post',
    'action' => 'login.php',
    'class' => 'login',
    'style' => array(
    'font-family' => 'Tahoma',
    'font-size' => '13px',
    ),
    'name' => 'login',
    'onsubmit' => 'return form_validate()',
    'innertext' => 'Enter your username and password here to login'
    );

    $element = new Element('form', $attributes); // ( [string] tag, [array] attributes )
    $element->appendChild($parents);

     
  • Logged In: NO

    This does seem useful and would bring this tool closer to the level of PHP's simplexml utility. I would assume the behavior would be similar to simplexml's addChild() and addAttribute() methods.

     
  • Iirc I've been doing it by using str_get_html on the desired HTML, then using array_splice to inject the information into the desired part of the dom - otherwise future finds don't find the information. Adding parent elements, etc, is left as an excercize for the reader/later.

     

  • Anonymous
    2011-07-23

    I am wanting to use the DOM as a template engine(I found great power in that while using it in Node.js and wanted to try to use it in PHP). But to do that I really do need this ability. Seems pretty basic but I can't see a way to add an element or HTML segment and then be able to find elements within that section.
    I like the format of $dom->find('#bd-unit', 0)->innertext .= "

    ";
    But to do that you would need to reparse the contents of innertext every time. Is there a way to do that?
    Even a form like
    $bd_unit = $dom->find('#bd-unit', 0);
    $bd_unit->innertext = str_get_html($bd_unit->innertext . "
    ");
    Would be better then nothing.

    Perhaps you can give me some insight into how to do this:

    I've been doing it by using str_get_html on the desired HTML, then using array_splice to inject the information into the desired part of the dom - otherwise future finds don't find the information.

    I might then be able to make up a generic function for myself to do this.
    Thanks!