-1

I am creating an element with this code. Setting the ID as it should be set. (Do I need the validateonparse?):

$sectionContainer = $dom->createElement('div', $section);
$sectionContainer->setAttribute("id", $section);
$sectionContainer->setIdAttribute("id", TRUE);
$dom->validateOnParse = true;
$divup->parentNode->insertBefore($sectionContainer, $divup);


echo 'avant'."</br>";
echo $section;
print_r($dom->getElementById($section)->getAttribute('id'));
echo 'apres'."</br>";

But I get this: Fatal error: Uncaught Error: Call to a member function getAttribute() on null

So it can't locate the element I just created, why?

benoit
  • 1
  • 1
  • 6

1 Answers1

0

Hey_ there,

the problem is not with $dom->validateOnParse = true;.

Your error comes from this line of code - $sectionContainer->setIdAttribute("id", TRUE);.

If you want to set id attribute of DOMElement like <div id="myId"></div> you only need $domElement->setAttribute("id", "myId"); which you already have.

DOMElement::setIdAttribute is actually indicating that this attribute is unique identifier which has nothing to do with the id="myId" attribute

(PHP 5, PHP 7)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

Description

public void DOMElement::setIdAttribute ( string $name , bool $isId )

Declares the attribute name to be of type ID.

Well it is not very clear what is type ID, but I can say that it is something different from id attribute of html element.

Check demo HERE

codtex
  • 6,128
  • 2
  • 17
  • 34
  • In your example, what does Before and After output stays for? There is only single output between Before and After. So it's confusing. – Meglio Nov 17 '17 at 02:17
  • I don't know also. I see that the code on this platform can be overwritten and I guess someone edit it... The important in this topic is that if you want to set the `id` attribute you do it with [**setAttribute**](http://php.net/manual/en/domelement.setattribute.php) instead [**setIdAttribute**](http://php.net/manual/en/domelement.setidattribute.php) – codtex Nov 20 '17 at 05:41
  • I think that code with Before and After only confuses things. – Meglio Nov 20 '17 at 11:22