, but I just thought maybe there is ...">

How can I run javascript automatically?

how can i automatically execute javascript?

I know <body onLoad=""> , but I just thought maybe there is another way to do this?

HTML:

 <html><head></head><body><div id="test"></div></body></html> 

JavaScript:

 <script>(function(){var text = document.getElementById('test').innerHTML;var newtext = text.replace('', '');return newtext;})();</script> 

I want to get the text inside the "test", replace certain parts and then output it to the browser.

Any ideas on how to do this? I would be grateful for any help. Thanks.

+7
javascript
source share
5 answers

If you don't want to use <body onload> , which is a good choice in terms of intrusive javascript, you can separate this and put the code like this:

 window.onload = function(){ // your code here }; 

Alternative:

Put your javascript code at the bottom of the page.

+16
source share

Place the script at the bottom of the page, outside the closing body tag.

+5
source share

It is REALLY easy! If you have a script in the "head" block, without a function identifier, it will start automatically as soon as the web page loads. For example:

<head> <meta charset="UTF-8"> <title>Redirection to www.mywebsite.org</title>

 <!-- This script initiates an automatic web page redirection, as the page is loaded --> <script type="text/javascript"> window.location = "http://www.mywebsite.com/" </script> 

</head>

+2
source share

If you do not want to use jQuery, use the native window.onload method:

 <script type="text/javascript"> function ReplaceText() { document.getElementById('test').innerHTML = document.getElementById('test').innerHTML.replace(/abc/g, "def"); } window.onload = ReplaceText; </script> 

Used for code:

 <div id="test">abc abc</div> 

Gives this output:

 def def 
+1
source share

A quick way, if you just want to debug, is to move what you want to do outside the function.

 <script type="text/javascript"> var text = document.getElementById('test').innerHTML; var newtext = text.replace('', ''); alert(newtext); </script> 

NB. I'm not sure what you hope to achieve with text.replace('', '') ?

0
source share

All Articles