Execute JavaScript functions in innerHTML

call javascript function inside innerhtml

There is big issue We found with innerHTML function. If you try to call javascript function inside innerhtml content then we will face this problem with various.
We need to always care about Cross browser issues with javascript method.

call javascript function inside innerhtml

For Ajax and adding the dynamically content in DOM we have actually we ways.
First is simple document.write function and second function is using innerHTML.

There is some cross browser issues with both the method. First I will talk about document.write.
If we use document.write in our DOM then there is no control over the content which we are adding through document.write

Basically when we use document.write then this function will execute or add the HTML content in DOM where we call this function.

If you want to avoid this this behavior I suggest use the innerHTML. But innerHTML method is also having some issues with nested innerHTML executing with 2 or 3 level with Major browsers.
Microsoft is now planning to launch the IE9 version. But in that version they are not supporting this kind of functionality.

So Major JS library developer need to think about new approach which will give some good alternate solution.

We can achieve the nested innerHTML but we need to do some very complex development in javascript.

With innerHTML method: The property is read/write for all objects except the following, for which it is read-only:
COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR. The property has no default value. Expressions can be used in place of the preceding value(s), as of Microsoft® Internet Explorer
5.

In this article I am going to give example about executing the simple javascript function in innerHTML.

function add_cont() {
var html_cont = 'javascript:alert(\'hello world\')">click for hello world test'+
 '<script> alert(\'tests\');'+
'var wordpressapi = document.createElement("div");'+
'wordpressapi.innerHTML = "some ad";<\/script>'
;
document.getElementById('test_htm').innerHTML = html_cont;
<div id="test_htm"></div>
javascript:add_cont()">Insert test div and text with javascript on click event.

Other best solution is all the traditional but still trusted.

document.write("<iframe src='inner_cont.html'>");
// ... Javascript code will goes here... //
document.write("</iframe&gt;");

Execute JavaScript functions in innerHTML
Execute JavaScript functions in innerHTML

I am still working on this issue to for adding nested innerHTML content.

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.