1

I'm using Zend_DOM_Query to read HTML elements using DOM.

<input type="text" class="a">
<input type="text" class="a">
<input type="text" class="a">

I load the html and find the <input> and then loop through the results.

foreach($inputss as $input){
}

What I actually want to do is add additional markup after each <input> like another input but of different class name <input type="text" class="b">. At the end my full markup will look like this

<input type="text" class="a">
<input type="text" class="b">
<input type="text" class="a">
<input type="text" class="b">
<input type="text" class="a">
<input type="text" class="b">

I keep seeing examples that use createElement() but nothing that seems to add HTML the way I need it added. Am I missing something?

2 Answers 2

2

The easiest way to do this is indeed with createElement:

foreach($inputss as $input){
    $newEl = $input->ownerDocument->createElement('input');
    $newEl->setAttribute('type', 'text');
    $newEl->setAttribute('class', 'b');
    $input->parentElement->insertBefore($newEl, $input->nextSibling);
}

Apart from the last line, which is admittedly a little verbose, this seems quite simple to me.

I suppose you could do this with createDocumentFragment and use appendXML to insert a string of HTML, but I don't see that that would be significantly easier or quicker.

NB that the reason this works is that within a Zend_Dom_Query_Result object are normal DOM objects, so you can use normal DOM methods on them.

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

Comments

1

I'm not sure if this this what you're looking for but this example can be helpfull:

$html = <<<HTML
<input type="text" class="a">
<input type="text" class="a">
<input type="text" class="a">
HTML;

$dom    = new DOMDocument();
$dom->loadHTML($html);

$xpath  = new DOMXPath($dom);
$nodes  = $xpath->query('//input[@class="a"]');
foreach ($nodes as $node) {
    $newNode = $node->cloneNode();
    $newNode->setAttribute('class', 'b');
    $node->parentNode->insertBefore($newNode, $node->nextSibling);
}

var_dump(($dom->saveHTML()));

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.