Niels B.
Niels B.

Reputation: 6310

Injecting arbitrary HTML snippets using JavaScript

I am looking for a way to inject arbitrary html snippets into a DOM node.

The reason I am asking is because I am developing some functionality for retargeting/tracking tags and my advertising partners use different approaches.

Some of them use script tags and they behave differently from other tags.

I have discovered that simply setting the innerHTML property on an arbitrary DOM node to the string <script src="foo"></script> is not going to work. Sure the tag is injected, but the code is not evaluated. I have to create a script node first, then set the src and type attributes and finally inject them.

I am looking for an approach to analyze HTML snippets and automatically and safely detect the correct/optimal way to inject them. I've already got jQuery, but if there are any libraries out there to make this easier, I'm happy to consider them.

Upvotes: 0

Views: 267

Answers (1)

Harrald Torenvlied
Harrald Torenvlied

Reputation: 28

Googling for "jQuery html string to elements", gave me: http://api.jquery.com/html/#html2

Upvotes: 1

Related Questions