1

I'm trying to change the ID of an element here:

http://moemonty.com/chirp/CHIRP-JSON-test.html

By using this line:

$('.databaseID').attr('id', 'test');

I would like to change the id of this line to test, so I can proceed to put in a pre-fix via a string and a variable from JSON data. But for now, I just wanted to see if I could replace it with test at this line:

<li class="databaseID" id="np-44701">

Thanks in advance.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
Moemonty
  • 109
  • 1
  • 1
  • 8
  • 4
    Did you test it? Did it work? Incidentally, you're selecting by the class-name. If you have more than one element of that class you'll end up with multiple elements with the same ID. – David Thomas Sep 29 '10 at 20:59
  • Other than the selection by class name (as @David pointed out), it looks like this would work. Not seeing any real problem here... – JasCav Sep 29 '10 at 21:02
  • possible duplicate of [jquery - changing an element id](http://stackoverflow.com/questions/347798/jquery-changing-an-element-id) – JasCav Sep 29 '10 at 21:03

1 Answers1

5

Yes, you can change the ID of an element with $().attr(). The code you give will work, but you should ensure that you only change one element:

$('li.databaseID:first').attr('id','test');

On the other hand, I'd urge you to think this through so you're sure that you really need to change the id of an element. I can't quite imagine the circumstance where it would be necessary.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • I have this, but when I look at the source of the page, the id has not changed. – Moemonty Sep 29 '10 at 21:10
  • It depends if you are viewing the original source or the current source - which browser are you using? – James Westgate Sep 29 '10 at 21:13
  • How are you viewing the source? Unless you're using something like Firebug (Firefox), Dragonfly (Opera) or Web Inspector (Chrome/Safari) to view the source in real-time js/jQuery manipulation won't show up. – David Thomas Sep 29 '10 at 21:14
  • No, it wouldn't have done. The source you see from "view source" is the original content downloaded from the server. If you want to see the code as modified by Javascript, use a tool such as FireBug (http://www.getfirebug.com/) or, if using IE, use Developer Tools. – lonesomeday Sep 29 '10 at 21:14
  • +1 for that last sentence *can't quite imagine where it would be necessary.* – David Thomas Sep 29 '10 at 21:15
  • I was using the browser, Firefox (CTRL + U) to view the source. However, I opened up the source by viewing it through the Firebug plug and I saw the change. – Moemonty Sep 29 '10 at 21:15