开发者

jQuery not finding all expected anchor links in HTML

I'm using jQueryPad to try out a bit of JavaScript and I'm stuck. Given I have the following HTML snippet:

<TABLE style="BORDER-COLLAPSE: collapse" id=phMain_Questions class=GridView border=1 rules=all cellSpacing=0><TBODY>
<TR class=GridViewHeader>
<TH scope=col>&nbsp;</TH>
<TH scope=col>&nbsp;</TH></TR>
<TR class=GridViewRow>
<TD><A id=hlQuestionDetails href="javascript:AddQuestionWindow_Open(3, 39, 'False');">This is a test question</A> </TD>
<TD><A href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$phMain$gvQuestions$ctl02$ctl00", "", true, "", "", false, true))'>Remove</A> </TD></TR>
<TR class="GridViewRow GridViewRowAlt">
<TD><A id=hlQuestionDetails href="javascript:AddQuestionWindow_Open(3, 40, 'False');">This is an option question.</A> </TD>
<TD><A href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$phMain$gvQuestions$ctl03$ctl00", "", true, "", "", false, true))'>Remove</A> </TD></TR></TBODY></TABLE>

What I want is to pick out all the a tags whose id attribute is hlQuestionDetails. My stab at this is:

var links = $("a#hlQuestionDetails");
alert($(links).length);

The number of a tags found is 1, but as you can see in the HTML, there are in fact 2 a tags with that name.

Can someone point what I'm doing wrong here, as I can't figure out why jQuery is leaving one of the a tags out.

EDIT:

In regards to the comments, I 开发者_开发知识库see the problem. The HTML was generated by an ASP.NET gridview control. So instead, I should use a class attribute I guess? Cheers. Jas.


Attribute id should unique identifier of element. You should use class attribute instead.


IDs must be unique in HTML, and the ID selector maps to document.getElementById, which returns the first matching element with that ID - give each element a class instead, and use the class selector:

var links = $("a.hlQuestionDetails"); 


IDs have to be unique in an HTML document (hence ID). Most browsers only return the first element if there are several elements with the same ID. Use classes instead

<A class="hlQuestionDetails" ...>This is a test question</A>

and retrieve the elements with the class selector:

var links = $("a.hlQuestionDetails");


The id should be a unique identifier in a html page. That's why getElementById(...) returns only 1 element. I guess jQuery does the same. Try using a class attribute and selector instead:

<a href=".." class="hlQuestionDetails">...</a>
<a href=".." class="hlQuestionDetails">...</a>
<a href=".." class="hlQuestionDetails">...</a>

alert($('a.hlQuestionDetails').length)


The ID for a tag should be unique and it should be within quotes. If you want to target several tags then use a dummy class, i.e. "Question" and then use $('.Question') to target your tags.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜