473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

executing javascript set with innerHTML in IE 7

I can't for the life of me figure out how to execute javascript inside
of div that was set using innerHTML or in my case using cloneNode and
replaceChild (not my idea to do this, I'm just fixing it). I have
tried it with and without the defer attribute. It will work fine in
firefox, but not IE.

<script type="text/javascript">
function setInnerHTMLAndExecScript (element, html) {
var newElement = element.cloneNode(false);
newElement.innerHTML = html;
element.parentNode.replaceChild(newElement,
element);
}

function loadDiv() {

var myHtml = '<script type="text\/javascript"
defer="defer">function testMe() {alert(\'test called\')}<\/
script><input type="button" value="test me" onclick="testMe();">';

setInnerHTMLAndExecScript(document.getElementById( 'myDiv'),myHtml);
}
</script>

<body onload="loadDiv();">
<div id="myDiv"></div>
</body>

Jul 14 '08 #1
6 2763
ca********@gmail.com wrote:
I can't for the life of me figure out how to execute javascript inside
of div that was set using innerHTML or in my case using cloneNode and
replaceChild (not my idea to do this, I'm just fixing it). I have
tried it with and without the defer attribute. It will work fine in
firefox, but not IE.
If it works in Firefox (which version?), you should consider that a happy
coincidence. You are dealing with a proprietary feature here. There is
nothing that guarantees a script that is included this way to be executed.
<script type="text/javascript">
function setInnerHTMLAndExecScript (element, html) {
var newElement = element.cloneNode(false);
You should indent (posted) code with two or four spaces per indentation
level instead. This way, in contrast to the Tab character, it is posted
and displayed uniformly among user agents, which makes it easier to read
(and to adapt). See also <http://www.jibbering.com/faq/#FAQ2_3and the
links therein.
newElement.innerHTML = html;
element.parentNode.replaceChild(newElement,
element);
}
This shallow cloning x as y, setting the content of y, and then replacing x
with y strikes me as being quite inefficient, to say the least. Changing
the content of x in the first place, i.e.

function setInnerHTMLAndExecScript(element, html)
{
element.innerHTML = html;
}

would probably have sufficed. However, one wants to use something
standards-compliant, like

var c;
while ((c = element.firstChild)) element.removeChild(c);

var input = element.appendChild(document.createElement("input" ));
input.type = "button";
input.value = "test me";

_global.testMe = function() {
window.alert("test called");
};

input.addEventListener("click", function() { _global.testMe(); }, false);

instead, whereas `global' can be a reference to the Global Object or to any
other user-defined object. Since (AFAIK) MSHTML does not support
EventTarget::addEventListener(), and addEvent() is buggy, you will need the
equivalent of

input.onclick = function() {
window.alert("test called");
};

as an alternative approach in that case.
HTH

PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jul 14 '08 #2
Thanks, and thank you for the tip of indenting code (I use tabs in my
editor)

when I try your code:

Firefox 3 complains of _global not being defined

Internet Explorer complains "could not get the type property"

Any ideas?

Jul 14 '08 #3
ca********@gmail.com wrote:
Thanks, and thank you for the tip of indenting code (I use tabs in my
editor)
You are welcome. Please also take heed of the recommendations about proper
quoting.
when I try your code:

Firefox 3 complains of _global not being defined
This is not a code factory; you should read postings more thoroughly:
>[...] whereas `global' can be a reference to the Global Object or to
any other user-defined object. [...]
I used `_global' in the code and `global' in the explanation, but you should
get the picture anyway.
Internet Explorer complains "could not get the type property"
Sorry, I forgot to consider a peculiarity of MSHTML that requires you to set
the `type' property of the object before you insert it in the DOM tree.
Therefore, this should work (tested positive in IE 7.0.5730.11):

var input = document.createElement("input");
if (input)
{
input.type = "button";
element.appendChild(input);
input.value = "test me";
}

The additional type-converting test here is useful in any case. Don't
forget to add runtime feature tests at least for all method calls.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8*******************@news.demon.co.uk>
Jul 14 '08 #4
On Jul 14, 2:21*pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
You are welcome. *Please also take heed of the recommendations about proper
quoting.
I love usenet!

This is not a code factory; you should read postings more thoroughly:

I used `_global' in the code and `global' in the explanation, but you should
get the picture anyway.
It's not a matter of not reading thoroughly, I will admit that after
over 10 years of exposure to the DOM, it and its functions, elements,
scopes, references, and after you add the cross-browser
inconsistencies - still leaves me confused. It's my comprehension that
is lacking.
>
Sorry, I forgot to consider a peculiarity of MSHTML that requires you to set
the `type' property of the object before you insert it in the DOM tree.
Therefore, this should work (tested positive in IE 7.0.5730.11):

* var input = document.createElement("input");
* if (input)
* {
* * input.type = "button";
* * element.appendChild(input);
* * input.value = "test me";
* }
This did actually work for both IE and Firefox, however...

Setting up the function and appending it to the input won't work for
my real-case scenario. Popping up a window is not what I'm really
trying to achieve. The script is already set in the html that I'm
returning from an Ajax call and it needs to run inside the div that I
insert it to. I didn't write any of this btw, I wouldn't have used
Ajax.

So I'll ask again if anyone else knows - is there any way to have
javascript execute if it's dynamically written to a div? For example,
html, with a script in it, returned from an Ajax response, inserted
into a div.

Jul 14 '08 #5
ca********@gmail.com wrote:
Thomas 'PointedEars' Lahn wrote:
>This is not a code factory; you should read postings more thoroughly:

I used `_global' in the code and `global' in the explanation, but you
should get the picture anyway.

It's not a matter of not reading thoroughly, I will admit that after over
10 years of exposure to the DOM, it and its functions, elements, scopes,
references, and after you add the cross-browser inconsistencies - still
leaves me confused. It's my comprehension that is lacking.
Well, what exactly do you not understand?
[...]
Setting up the function and appending it to the input won't work for my
real-case scenario. Popping up a window is not what I'm really trying to
achieve. The script is already set in the html that I'm returning from an
Ajax call and it needs to run inside the div that I insert it to. I
didn't write any of this btw, I wouldn't have used Ajax.
IMHO the best way to use the current approach is to have the HTTP server
respond with a message containing JSON for an object that has properties
both for the function code and for the HTML code. Then evaluate the
function code from the former and create the DOM nodes from the latter. WFM.

<http://json.org/>
So I'll ask again if anyone else knows - is there any way to have
javascript execute if it's dynamically written to a div? For example,
html, with a script in it, returned from an Ajax response, inserted into
a div.
What you are asking for exactly apparently cannot be done both reliably and
efficiently. So you will have to adapt your client-side *and* server-side
code to achieve production quality.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8*******************@news.demon.co.uk>
Jul 15 '08 #6
On Jul 14, 3:40*pm, cantrel...@gmail.com wrote:
I can't for the life of me figure out how toexecutejavascript inside
of div that was set using innerHTML or in my case using cloneNode and
replaceChild (not my idea to do this, I'm just fixing it). I have
tried it with and without the defer attribute. It will work fine in
firefox, but not IE.
The fact it works in Firefox is strangely odd. Search the archives for
loadHTMLFragment and my name. The articles you find, and the links
within them, will explain why it doesn't work and ways to get it to
work. The function loadHTMLFragment does pretty close to what you are
wanting to do. Instead of calling someElement.innerHTML =
someFragment;, you would do loadHTMLFragment(elemID,someFragment) and
the function does the rest.

http://groups.google.com/group/comp....4ddde766fc0caf

Good luck with it.

Randy
Jul 22 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Astra | last post by:
Hi everybody Wonder if you could help me out. I created a simple JavaScript routine to enable a user to click backwards and forwards between small news articles. This routine works fine in IE...
5
by: ZildjianB | last post by:
Hi All, I hope you can help me with this, as I have done some exhaustive searching over the past couple days and cannot find a solution. What I am trying to do is dynamically update an image...
7
by: e | last post by:
I've been having an extremely difficult time finding an answer to this in IE / js groups, so I thought I'd try here. I've got an aspx page that delivers loads of report data into custom-named...
2
by: Jon Slaughter | last post by:
When a user clicks a link I have it open up a file in a div using ajax. my code is <a href="#Find" onclick="javascript:jah('Find.html','content');">Find</a><br /> Where Find.html is an html...
13
by: mowsen | last post by:
Hello Group, i'm using a little "ajax" loader script to dynamically load files into different "div" tags on my main site. the code for this part looks like: function loader() { var args =...
8
by: Pratik Patel | last post by:
Hello, I used innerHTML to assign HTML content. but in my HTML page content have also some javascript function and it will run when page load. bu when HTML code assgin thru innerHTML then this...
15
by: rage3324 | last post by:
I am posting html onto my main page between div tags using xmlhttprequest and innerhtml. The html I am posting has javascript inside which I am executing using the eval() function. However, the...
2
by: smartic | last post by:
i'm having three lists when i select from any one the others be visible by hierarchy but it takes to long to write my code is there is another away to write this code like XML that is my javascript...
4
by: karuppiahdas | last post by:
Hi I am facing a problem in executig the javascript in innerHtml. I got a login screen(jsp page), with two form in the bodyl.One form is wrapped by a div tag.Which has got the login...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.