getelementbyid动态创建的元素不能正常工作

问题描述:

我正在用这段代码创建一个元素。设置它应该设置的ID。 (我需要的validateonparse?):getelementbyid动态创建的元素不能正常工作

$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>"; 

但我得到这个: 致命错误:未捕获的错误:调用一个成员函数的getAttribute()上的空

所以它无法找到元素我刚创建,为什么?

Hey_那里,

的问题不在于$dom->validateOnParse = true;

您的错误来自此行 - $sectionContainer->setIdAttribute("id", TRUE);

如果你想设置DOMElement的id属性,就像<div id="myId"></div>你只需要你已经有的$domElement->setAttribute("id", "myId");

DOMElement::setIdAttribute实际上是表明该属性是唯一的标识符,无关与id="myId"属性

(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.

那么它是不是很清楚什么是类型ID,但我可以说,这是与html元素的id属性不同。

检查演示HERE

+0

在您的例子,什么是之前和之后输出停留? Before和After之间只有一个输出。所以它很混乱。 – Meglio

+0

我也不知道。我发现这个平台上的代码可以被覆盖,我想有人编辑它......这个主题的重要之处在于,如果你想设置'id'属性,你可以使用[** setAttribute **](http ://php.net/manual/en/domelement.setattribute.php)而不是[** setIdAttribute **](http://php.net/manual/en/domelement.setidattribute.php) – codtex

+0

我认为代码之前和之后只会混淆事物。 – Meglio