felix
felix

Reputation: 11542

DOM Elements with same id and jQuery

Hi I have multiple elements with the same structure in my application. Second div element's id varies as per the comment id in the db which is unique. There are elements with the id 'vote_up' and 'vote_down'. This gets repeated for each comment.What happens is that, as I mentioned, there are multiple comments. I want to perform an Ajax request. First of this structure functions properly using ajax, but the rest does an http request. Btw I am developing a rails application and I am using jQuery.

<div id="post_comment">
john<i> says </i> Comment<br/>

<div id="comment_10_div">
**<form action="/comments/vote_up" id="vote_up" method="post">**
         <div style="margin:0;padding:0;display:inline">
               <input name="authenticity_token" type="hidden" 
               value="w873BgYHLxQmadUalzMRUC+1ql4AtP3U7f78dT8x9ho=" />
         </div>
     <input id="Comment_place_id" name="Comment[post_id]" type="hidden" value="3" />
     <input id="Comment_id" name="Comment[id]" type="hidden" value="10" />
     <input id="Comment_user_id" name="Comment[user_id]" type="hidden" value="2" />
     <input name="commit" type="submit" value="Vote up" />
</form>

<label id="comment_10">10</label>

**<form action="/comments/vote_down" id="vote_down" method="post">**
        <div style="margin:0;padding:0;display:inline">
            <input name="authenticity_token" type="hidden" 
            value="w873BgYHLxQmadUalzMRUC+1ql4AtP3U7f78dT8x9ho=" />
        </div>
    <input id="Comment_place_id" name="Comment[place_id]" type="hidden" value="3" />

    <input id="Comment_id" name="Comment[id]" type="hidden" value="10" />
    <input id="Comment_user_id" name="Comment[user_id]" type="hidden" value="2" />
    <input name="commit" type="submit" value="Vote Down" />
</form>
</div>      

Can you please help me to solve this Thanks

Upvotes: 3

Views: 4253

Answers (2)

Patrick Klingemann
Patrick Klingemann

Reputation: 9014

Expanding upon what's already been said, the way you should implement this is:

<div id="comment_10" class="comment">
</div>

Then you can select all comments with:

$('.comment')

or a single comment with:

$('#comment_10")

Upvotes: 4

Ain Tohvri
Ain Tohvri

Reputation: 3035

Yes, as Matti mentioned above, by the W3C standards ID has to be unique. A nice workaround would be to postfix comment's db ID, e.g. <input id="Comment_39127438"...

Upvotes: 4

Related Questions