views:

97

answers:

3

Is it possible to have some sort of Id scoping when manipulating DOM with JS?

I use jQuery as my JS framework.

For example:

Is there any mechanism that would allow to select someDiv children of first or someDiv children of second, or do all ids on the page have to be unique? I know this would be doable using classes (jQuery selector would be .first>.someDiv), but is this doable for the id property as well? ---------- Edit: for clarification, here's a more complete example: File picture_editor.php: ... JS script for this editor, that needs to manipulate picture_id

...

File main_view.php:

...

Script that manipulates picture_id

...

include(picture_editor.php);

...

Now in the case where picture_editor is included in a file (like main_view) that has an element with the same id as elements in picture_editor, something somewhere is going to stop working (whether it's some script in picture_editor or main_view, or both). Question: How do you go around that?

A: 

All ids need to be unique, so I don't think so.

Jourkey
+1  A: 

HTML id attribute, Definition and Usage:

  • The id attribute specifies a unique id for an HTML element.
  • The id must be unique within the HTML document.
  • The id attribute can be used by a JavaScript (via the HTML DOM) or by
    CSS to make changes or style the
    element with the specified id.

From http://www.w3schools.com/tags/att%5Fstandard%5Fid.asp

karim79
A: 

If your ids are not unique, then your page is not valid HTML. Rethink your structure if you have non-unique id.

As for whether jQuery supports it, it's unlikely, as it should never meet that scenario.

Eric
Unfortunately, many (most?) browsers work "well enough" that having more than one element with the same ID is allowed, *and* selecting an element by ID 'works' (it is not clear if the same element is selected across browsers, though) using document.getElementById.
BryanH