How can I add content to the newly created tag? For example, I need to create like the following tag:
<script src="https://stackoverflow.com/">
alert("ok");
</script>
I have implemented the following code:
$finalDom = new DOMDocument;
$finalDom->loadHTML("", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");
$finalDom->appendChild($newElement);
The result of this code is an only empty script tag:
<script src="https://stackoverflow.com/"></script>
you can use createTextNode to add text node for the element, as
....
$newElement->setAttribute("src", "https://stackoverflow.com/");
$finalDom->appendChild($newElement);
$newElement->appendChild($finalDom->createTextNode('your text here'));
....
You can set the content using $textContent property of DOMElement .
$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");
$newElement->textContent = 'alert("ok");';
You can use any of these three options for adding text
elem.append(document.createTextNode(text))
elem.innerHTML = text
elem.textContent = text
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.