开发者

Getting every element with a specific ID (jQuery)

I need to get every element with a specific id, get the parent of the object, and set its ID.

How would I do this?

I have this code:

<li id="edge_top">&nbsp;</li>
<!-- Menu Items Here     -->
<li id="not_selected"><a id="selection_link" href="index.htm">Home</a></li>
<li id="not_selected"><a id="selection_link" href="page1.htm">Subitem 1</a></li>
<li id="not_selected"><a id="selection_link" href="page2.htm">Subitem 2</a></li>
<!-- Menu Items End Here -->
<li id="edge_bottom">&nbsp;</li>

I need to find all the anchor elements with the id "selection_link", get the parent (the "list item开发者_如何转开发" element [li]) and set its ID to "selected". How would I do this with jQuery? I'll be using the conditioning to determine if the li element will actually be allowed to get the new ID. (if the URL matches the href property of the anchor element).


HTML specification specifies that an ID should only be applied to 1 element. You can't have more then one element with the same ID.

In this case, it's better to use classes.

TO select by class:

$(".classname")...

EDIT: An example based on your code:

<li class="edge_top">&nbsp;</li>
<!-- Menu Items Here     -->
<li class="not_selected"><a class="selection_link" href="index.htm">Home</a></li>
<li class="not_selected"><a class="selection_link" href="page1.htm">Subitem 1</a></li>
<li class="not_selected"><a class="selection_link" href="page2.htm">Subitem 2</a></li>
<!-- Menu Items End Here -->
<li class="edge_bottom">&nbsp;</li>

<script type="text/javascript">
$(document).ready(function(){
    $(".selection_link").parent().removeClass("not_selected").addClass("selected")
});
</script>


You need to use classes for that. In HTML you not allowed to use ID's multiple times.


The id attribute should be unique across your XHTML document, so this question is not really valid.

Although this may work if you really insist:

$("[id=xx]")


$('li a').each(function(){

    if ($(window).attr('location').href.match($(this).attr('href'))) {
        //example with class
        $(this).parent().addClass('selected');
        // example with id
        $(this).parent().attr('id', 'selected');

    }

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜