tags:

views:

43

answers:

5

How can I select the first tag with center id name in sample below code?

<div id=first>
     <div id=center></div>
</div>
<div id=first>
     <div id=center></div>
</div>
+1  A: 

ids are meant to be unique. Correct your html first.

http://www.w3.org/TR/html401/struct/global.html#h-7.5.2

Entendu
+1  A: 

You don't, that is not standard HTML.

The id attribute specifies a unique id for an HTML element. The id must be unique within the HTML document.

http://www.w3schools.com/tags/att_standard_id.asp

nico
+3  A: 
div = document.getElementById("center");

I'm assuming you copy-pasted twice which is why the code is duplicated. If not, you need to change those IDs to classes (ID must be unique in a document).

Also, put quotes around attributes (id="center")

Coronatus
+1 Does this question really call for a library? Thanks for the javascript answer.
harpo
A: 

First thing, "id"s are unique, meaning you should never have two tags with the same id. You should use classes instead, which are meant for tags that have several things in common.

Second, I would look over XHTML validation, as that above is invalid:

http://www.w3schools.com/xhtml/

I don't know if that will solve your problem or not. If you are using jQuery you can do something simple such as:

$('.center:first')

Your HTML would look something like this:

<div class="first">
     <div class="center"></div>
</div>
<div class="first">
     <div class="center"></div>
</div>
Kerry
A: 

You can use Prototype to select that element - however it is not valid HTML to name different nodes the same id.

using Prototype to select the first one using your code

$$("#center")[1];

If you need to keep them together use a class then you can loop through them like this

$$(".center").each(function(item){
  //Fun scripts
});
Geek Num 88
A 50KB (or so) library for selecting by ID? Are you crazy?
Coronatus
If the OP wanted to use the code as it stands - I would suggest the Prototype library. If they just need to get that element then `document.getElementById("")` will do what they need
Geek Num 88