0

I'm trying to replace a part of my HTML code with JS but doesn't work.

I have the next code:

<td id="one"><a href="servlet.jsp?account='old'" >old</a></td>

And i'm want to change "old" for "new", like this:

<td id="one"><a href="servlet.jsp?account='new'" >new</a></td>

Then i'm using JS because i need to do with this using the method replace(), then, my JS is:

var old = "old";
var rep = "new";
var elem = document.getElementById("one");
var text = elem.innerHTML;
text = text.replace(old,rep);
elem.innerHTML = text;

I tryed and search but always i founded the same.

Any suggestion are welcome.

(I wrote the cody by memory because i'm not in the office and it's more complex) i'll try tomorrow)

5
  • 1
    Why are you using quotes in you GET argument values? Besides that, please never use string operations to modify DOM elements. Commented Jul 16, 2013 at 15:38
  • Why are you using replace instead of just overwriting? Commented Jul 16, 2013 at 15:38
  • 1
    SyntaxError: Unexpected token new. Learn how to debug JavaScript. Commented Jul 16, 2013 at 15:40
  • Using elem, get the child <a> element, and use replace on its href property instead. You shouldn't have to reset the innerHTML of its parent Commented Jul 16, 2013 at 15:40
  • I wrote the cody by memory because i'm not in the office and it's more complex i'll try tomorrow "new" var i didn't used it's a example only for tell tthis. Commented Jul 16, 2013 at 15:47

2 Answers 2

7

Because "new" is a reserved word in JavaScript.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

answered Jul 16, 2013 at 15:38
Sign up to request clarification or add additional context in comments.

1 Comment

... which throws a syntax error and hence the code is not even executed.
-1

No clue - it works for me. However, your method is very insecure; instead of working on elem.innerHTML, it would be much better to use elem.getAttribute and elem.setAttribute for direct access to href. Otherwise, imagine what would happen if your old happens to be "ref", or something similar that coincidentally exists before your intended term...

EDIT: doh, didn't even notice the var name>.<

answered Jul 16, 2013 at 15:41

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.