1

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?

asked Jul 29, 2010 at 19:03

3 Answers 3

2

It would , if you want to replace that text and put at certain part of the page, you should go about something like this:

var str="textiwanttoreplace";
var el = document.getElementById('element_id');
el.innerHTML = str;

So instead of:

document.write();

Use:

var el = document.getElementById('element_id');
el.innerHTML = str.replace("textiwanttoreplace", "Good Morning");

Just replace element_id with the id of the element in which you want to put the result of the text.

Update:

Based on your comment, I tested it and it works, you can check it out here:

http://jsbin.com/odipu3

answered Jul 29, 2010 at 19:07
Sign up to request clarification or add additional context in comments.

1 Comment

changed to that, but I can't seem to get it to work. Am I missing something?(new code in the question)
1

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.

answered Jul 29, 2010 at 19:09

1 Comment

no only once, how would I do that? I'm more or less a total noob when it comes to javascript
0

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>
answered Jul 29, 2010 at 19:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.