tags:

views:

55

answers:

3

I'm having trouble getting this to work...it just replaces the entire page with the result

var str="textiwanttoreplace";
var el = document.getElementById('welcome');
el.innerHTML = str;
var date = new Date();
var hours = date.getHours();


if (hours >= 8 && hours < 13) {
    el.innerHTML = str.replace("textiwanttoreplace", "It's 8 and 13");
} else if (hours >= 13 && hours < 18) {
    el.innerHTML = str.replace("textiwanttoreplace", "It's 13 and 18");
} else if (hours > 18 && hours <= 23) {
    el.innerHTML = str.replace("textiwanttoreplace", "It's 18 and 23");
} else {
    el.innerHTML = str.replace("textiwanttoreplace", "Hello");
}

edit: changed, and now I'm not seeing any results am I missing something?

+2  A: 
Sarfraz
changed to that, but I can't seem to get it to work. Am I missing something?(new code in the question)
kevin
@kevin: see my updated answer please.
Sarfraz
awesome that worked thanks
kevin
+1  A: 

document.write is BAD practice.

Does the text (that you want to replace) exist in multiple locations in your document? The right way to do this text replacement is to traverse the DOM and replace the text content of the specific element(s) that contain said text.

Matt Ball
no only once, how would I do that? I'm more or less a total noob when it comes to javascript
kevin
A: 

You'll want to narrow down the parent of the text you're to replace. You could do it against the entire document, but it will be extremely inefficient.

<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript></script>
<script type="text/javascript">
    $(document).ready(function() {
       $("div.replace-me").text($(this).text().replace('will replace', 'Good morning'));
     });
</script>
ryan