2

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>
2

3 Answers 3

2

You can set the content using $textContent property of DOMElement.

$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");

$newElement->textContent = 'alert("ok");';
Sign up to request clarification or add additional context in comments.

Comments

2

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'));
....

Comments

-1

You can use any of these three options for adding text

elem.append(document.createTextNode(text))
elem.innerHTML = text
elem.textContent = text

2 Comments

Are you answering in the context of javascript? This is a php question.
this is a PHP question

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.