473,777 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

innerHTML and SCRIPT tag

PJ
Greetings...

I have stumbled upon a small problem.

I use Ajax to retrieve part of a page I need to update. I update a DIV
element with the HTML contents I get from another page.

It works fine.

However the HTML have a SCRIPT tag that the browser should process, but
it doesn't.

Here's an example:

--- pageX.aspx ---
<table>
<tr>
<td>Table 01</td>
</tr>
</table>
<script>
alert("HI");
</script>
--- end pageX.aspx ---

--- page on browser ---
<div id="divContents "></div>

<script>
divContents.inn erHTML = getHtmlFromPage ("pageX.aspx ");
</script>
--- end page on browser ---

When the prowser gets the "pageX.aspx " and updates the contents of the
'divContents' it displays the table, but it didn't process the script.

What am I doing wrong?

Regards,

PJ
http://pjondevelopment.50webs.com

Jul 19 '06 #1
17 34722
PJ said the following on 7/19/2006 10:43 AM:
Greetings...

I have stumbled upon a small problem.

I use Ajax to retrieve part of a page I need to update. I update a DIV
element with the HTML contents I get from another page.

It works fine.
It works in IE, it won't work in any other browser since you are relying
on an IE-shortcut to get a reference to the div tag.
However the HTML have a SCRIPT tag that the browser should process, but
it doesn't.
Script blocks inserted via innerHTML don't get executed in any browser
other than NS6

<snip>
When the prowser gets the "pageX.aspx " and updates the contents of the
'divContents' it displays the table, but it didn't process the script.
What am I doing wrong?
You will have to search through your HTML block and find the script
elements and insert them using createElement to get the script blocks
executed.

var d =
document.getEle mentById('divCo ntents').getEle mentsByTagName( "script")
var t = d.length
for (var x=0;x<t;x++){
var newScript = document.create Element('script ');
newScript.type = "text/javascript";
newScript.text = d[x].text;
document.getEle mentById('divCo ntents').append Child(newScript );

}
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Temporarily at: http://members.aol.com/_ht_a/hikksnotathome/cljfaq/
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 19 '06 #2

Randy Webb wrote:
You will have to search through your HTML block and find the script
elements and insert them using createElement to get the script blocks
executed.

var d =
document.getEle mentById('divCo ntents').getEle mentsByTagName( "script")
var t = d.length
for (var x=0;x<t;x++){
var newScript = document.create Element('script ');
newScript.type = "text/javascript";
newScript.text = d[x].text;
document.getEle mentById('divCo ntents').append Child(newScript );
I haven't seen this method before. I've been taking another approach
that uses eval and wonder if one way is superiour (faster, more robust
etc).

function update(element, html) {
document.getEle mentById(elemen t).innerHTML=ht ml;

var re = /<script\b[\s\S]*?>([\s\S]*?)<\//ig;
var match;
while (match = re.exec(html)) {
eval(match[1]);
}
};

Thanks,
Peter

Jul 20 '06 #3
pe**********@gm ail.com wrote:
Randy Webb wrote:
>You will have to search through your HTML block and find
the script elements and insert them using createElement to
get the script blocks executed.

var d =
document.getEl ementById('divC ontents').getEl ementsByTagName ("script")
var t = d.length
for (var x=0;x<t;x++){
var newScript = document.create Element('script ');
newScript.type = "text/javascript";
newScript.text = d[x].text;
document.getEl ementById('divC ontents').appen dChild(newScrip t);

I haven't seen this method before. I've been taking another approach
that uses eval and wonder if one way is superiour (faster, more robust
etc).

function update(element, html) {
document.getEle mentById(elemen t).innerHTML=ht ml;

var re = /<script\b[\s\S]*?>([\s\S]*?)<\//ig;
var match;
while (match = re.exec(html)) {
eval(match[1]);
}
};
They are not equivalent so comparison is irrelevant. If you - eval -
code - var - will create function local variables instead of global ones
and function declarations will be inner functions not global ones.

Richard.
Jul 20 '06 #4
pe**********@gm ail.com said the following on 7/19/2006 8:27 PM:
Randy Webb wrote:
>You will have to search through your HTML block and find the script
elements and insert them using createElement to get the script blocks
executed.

var d =
document.getEl ementById('divC ontents').getEl ementsByTagName ("script")
var t = d.length
for (var x=0;x<t;x++){
var newScript = document.create Element('script ');
newScript.type = "text/javascript";
newScript.text = d[x].text;
document.getEl ementById('divC ontents').appen dChild(newScrip t);

I haven't seen this method before. I've been taking another approach
that uses eval and wonder if one way is superiour (faster, more robust
etc).
Yes, one way is superior to the other. You can read Richard's reply for
an explanation of the scope issues involved with the eval portion.

Second. Where is your script block appended? And, how would you go about
removing it? With the above code, you can simply set the innerHTML of
divContents to '' and you have removed *all* script blocks that were
appended. Meaning, when a new request is made, you are not retaining all
of your old script blocks but they are discarded.

And that is not even getting into the aspects of eval.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Temporarily at: http://members.aol.com/_ht_a/hikksnotathome/cljfaq/
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 20 '06 #5
Second. Where is your script block appended?

If I do

var d = document.getEle mentById('my_di v');
d.innerHTML = htmlInAjaxRespo nse;

and htmlInAjaxRespo nse has script blocks in it, then are the script
blocks not inside "my_div"? If not where are they? If so then will they
not be removed when I use d=''; ?

Thanks,
Peter

Jul 20 '06 #6
pe**********@gm ail.com said the following on 7/19/2006 10:14 PM:
>Second. Where is your script block appended?

If I do

var d = document.getEle mentById('my_di v');
d.innerHTML = htmlInAjaxRespo nse;

and htmlInAjaxRespo nse has script blocks in it, then are the script
blocks not inside "my_div"?
The code for them is, the code that got executed, and its scope, is not.
If not where are they? If so then will they not be removed when I use d=''; ?
There is a difference between the code you read in and execute (it's
source) and the code that is actually executed, along with it's scope chain.

Besides, even if they are exactly the same results (they aren't always),
the first *has* to be more efficient since it isn't starting up the
parser every time you eval something.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Temporarily at: http://members.aol.com/_ht_a/hikksnotathome/cljfaq/
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 20 '06 #7
"Randy Webb" <Hi************ @aol.comwrote in message
news:3P******** *************** *******@comcast .com...
PJ said the following on 7/19/2006 10:43 AM:
>Greetings...
*snip*
>However the HTML have a SCRIPT tag that the browser should process, but
it doesn't.

Script blocks inserted via innerHTML don't get executed in any browser
other than NS6
One wrinkle to this.

IE will parse/execute a script block injected into a DIV - however you must
first set the innerHTML property to "null" THEN load the content as in:

document.getEle mentById(Elemen tID).innerHTML = null;
document.getEle mentById(Elemen tID).innerHTML = NewContent;

I've not (yet?) been able to get FireFox to do the same thing (at least not
without the kind of DOM parsing you mention).

I use the above extensively in a windowing system for intranet applications
(although this works in a normal HTML file we use it in corporate HTA
applications).

Jim Davis
Jul 20 '06 #8

"Jim Davis" <ne********@vbo ston.comwrote in message
news:dr******** *************** *******@giganew s.com...
"Randy Webb" <Hi************ @aol.comwrote in message
news:3P******** *************** *******@comcast .com...
>PJ said the following on 7/19/2006 10:43 AM:
>>Greetings.. .

*snip*
>>However the HTML have a SCRIPT tag that the browser should process, but
it doesn't.

Script blocks inserted via innerHTML don't get executed in any browser
other than NS6

One wrinkle to this.

IE will parse/execute a script block injected into a DIV - however you
must first set the innerHTML property to "null" THEN load the content as
in:

document.getEle mentById(Elemen tID).innerHTML = null;
document.getEle mentById(Elemen tID).innerHTML = NewContent;
Actually I've fibbed a little. More information:

To get the injected script to actually run in IE you also need to set the
"defer" attribute on the script element to "defer" as in:

<script type="text/javascript" defer="defer">
alert("My Script's a runnin'!");
</script>

So to just let injected script run (in IE) you need to just set the "defer"
attribute.

Setting the innerHTML to null is not actually required to run the script
however it's still a VERY good idea. The reason is because IE will not
automatically over-write any existing functions unless you do this. Setting
the innerHTML to null actually unloads all functions defined in the
DIV-contained script elements and allows new ones of the same name(s) to be
created.

For example if you had a function called "Init()" in multiple pieces of
content IE would always run the first instance loaded into the DIV UNLESS
you "null" the container before loading the subsequent block.

The "pages" in my applications (all content retrieved via an XMLHttpRequest
call and injected into a DIV ) all reference a created psuedo-scope called
"Page" and have certain standardized functions ("Page.Init( )" which
initilizes the page, "Page.Denit ()" which run when the page is unloaded and
"Page.Renit ()" which is run when the page is resurfaced but not reloaded).

The nulling of the container DIV is neccessary to allow the replacement
functions to be properly added to the model.

Jim Davis
Jul 20 '06 #9

"Jim Davis" <ne********@vbo ston.comwrote in message
news:MK******** ************@gi ganews.com...
>
Oh - one other imprtant thing: if you set the injected script to "defer"
then FireFox will run it as well... but it has other troubles with
overwriting functions.

Still if you just plain want to run an "alert()" like the OP then "defer"
seems to be your friend.

Jim Davis
Jul 20 '06 #10

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

Similar topics

4
6553
by: RobG | last post by:
I know you aren't supposed to use innerHTML to mess with table structure, but it seems you can't use it just after a table without damaging the containing element. I added a table to a div using createElement methods, then added a bit of extra text using innerHTML, only to find most of the attributes removed from the table. Below is a script that calls the same code to add a table inside a div. It adds an onclick to the div and...
4
1766
by: bissatch | last post by:
Hi, I have the following simple HTML page. I am trying to get the innerHTML of the table element, "xmltable". I do intend to change the innerHTML of this table but at this stage I am having simple problems. When I create the following page, note that 'onload' the loadfunction() function is run. In this function all that is happening is that it is chacking that the browser supports getElementById and then display an alert with the...
8
8441
by: McKirahan | last post by:
Firefox does not reflect selected option via innerHTML How do I get Firefox to reflect selected option values? <html> <head> <title>FFinner.htm</title> <script type="text/javascript"> function clicks() { document.getElementById("t1").value =
1
2062
by: Paul | last post by:
Here is my current code: ------------ <script runat=Server> void Page_Load(object sender, EventArgs e){ if (!IsPostBack){ myDiv.InnerHtml = "Original Content"; } //On Postback, should equal "Original Content and New Content" string strContent = myDiv.InnerHtml; }
4
1955
by: robert.waters | last post by:
Hello, When the following page is executed in IE6, it generates script errors ('object expected') for any function that is declared in an external ..js file. Why is this???? This code works in Firefox 1.07 and 1.5. (The following code, when the body's onload event is triggered, simply rewrites the page using documentElement.innerHTML) //------------test.html-------------------- <html> <head>
2
1051
by: Edwin Knoppert | last post by:
Can this be done? I want to avoid the alert comming back on back and forwards navigation. Hmm, maybe a var (boolean)? (Don't mention the js execution-flow itself, it is presented odd ) <div id="div_msgbox_onloadalertmb"> <script language=javascript> function msgbox_onloadalertmb(){
11
11944
by: tlyczko | last post by:
Hello Rob B posted this wonderful code in another thread, http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/c84d8538025980dd/6ead9d5e61be85f0#6ead9d5e61be85f0 I could not figure out how to reply to the thread per se using Google Groups and so please forgive me for cutting and pasting (I emailed him but he may not have time to check his email), and I am hoping someone might be able to tell me how I can change this...
3
3169
sabesneit
by: sabesneit | last post by:
Hi, I'm tring to execute some javascript with innerHTML but nothing happen, here a simplified example: <html> <head> <title>this doesnt work!</title> <script language="javascript"> function DoSomething() { document.getElementById("div1").innerHTML = "<script language=\"javascript\">\n alert(\"hello world\");\n <\/script>"; }
2
5161
by: Tereska | last post by:
I want to delete script added before. I'm adding script dynamically and i'm removing later. Why it is still working? I have something like this: <html> <head> <title>JS Script Remove</title> </head>
1
2129
by: IntoEternity | last post by:
Hello, I found a script for innerHTML, which has a basic expand / collapse function. However, when it comes to table cells … it craps out. I know some form of toggle function needs to be added, something the lines of this function toggle(id) { var tr = document.getElementById(id); if (tr==null) { return; } var bExpand = tr.style.display == ''; tr.style.display = (bExpand ? 'none' : ''); } function Toggle_h1() { toggle('row1');...
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9464
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8954
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5368
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5497
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.