I have problem with the follwoing situation:

I have several divs in a page, none has an id. What I want to do is when I click on one of these divs its id is set to "current" and when I click on another div its id is set to "current" but all the ids of the other divs are erased.

Don't laugh at me ,':(, I myself too think this is impossible, but if anyone think that it is doable please show me how. It would help me a lot if it could be done.

Thank you in advance

  • Any framework available? Or should it be native javascript? Roland Franssen over 9 years ago

2 answers

This was chosen as the best answer

That isn't unusual at all, and is something for which I would use jQuery. I would suggest using adding and removing classes and not ids as ids are meant to be specific to a particular element and not changing. I would also give each of the active divs a specific class so that later you could add divs that don't respond to clicks. Try something like the following.

$(document).ready(function() {
  $('.activate_with_click').click(function() {
Answered over 9 years ago by kainosnous
  • Yep; either a class or a custom attribute would be preferable to a dynamic ID. Nathan Duran over 9 years ago
  • Thank you. Although I know nothing about JQuery, but what you describe is what I want. As you said this is not unusual. I also have found this, which is really what I understand the most: <div onclick="setID(this);">. So the part that I didnt thought of is to supplay "this" as parameter to the setID function. The javascript part: function setID(caller){ caller.id = 'current'; } of course before the line caller.id = 'current' I can erase the id/class of the div that has the id/class 'current'. mnish over 9 years ago
  • I would highly recommend learning jQuery. It makes this sort of thing trivial. The above code can be included in a script and doesn't have to leave anything in the HTML (accept the .activate_with_click classes, but you could make it fit your existing markup). Not only does that keep markup separate, but makes editing/updating easier. jQuery is very powerful, and yet lightweight (about the size of this site's logo, and it can be cached). It's worth it. kainosnous over 9 years ago
  • Native javascript can be unobtrusive just as well. Basicly dont include a framework just for fetching some ID, often its 99% overkill. If you are an OOP programmer i would recommend "PrototypeJS" however. Roland Franssen over 9 years ago

It really isnt that hard.. first you bind click events to all specific dom elements.

If an element is clicked then check if a DOM element with id "current" exists, if so you fetch it (document.getElementById) and erase the id attribute, now you can safely assign "current" to the element being clicked.

This way you prevent duplicate ids in the DOM.

Answered over 9 years ago by Roland Franssen