views:

2344

answers:

3

I'm using jQuery 1.3.2:

<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>

I've got the following html:

    <div id="container-div">
        <div id="package_1">
            <div>Package_1</div>
            <div id="package-content"></div>
        </div>
        <div id="package_2">
          <div>Package_2</div>
          <div id="package-content"></div>
        </div>
    </div>

I'm trying to select all the "package-content" elements with a jQuery selector. I thought i could do the following but it's not working as expected:

$('#package-content')

This is only returning the first element in the list - which is what i would expect from getElementById("package-content") but I thought jQuery would return an array of all the elements. What am i missing in my understand of the jQuery selector for div ids?

I wrote the following tests for figure out what was going on but it didn't help with my understanding other than to prove it was only selecting the first element.

alert($('#container-div').find('#package-content').size()); = 2
alert($('#package-content').size()); = 1
alert($('#package-content').parent().attr('id')); = package_1

$("#package-content").each(function() {
    alert('parent: ' + $(this).parent().attr('id') + ' child: ' + $(this).attr('id')); = parent: package_1 child: package-content
});
+5  A: 

id is supposed to be a unique value to identify a particular element. You can't have two divs with the same one. You could try using a class and $('.package-content') instead.

Chad Birch
I misread the jQuery docs on this one - http://docs.jquery.com/Selectors/id#id - clearly states it only selects one #id.
Rick Hochstetler
A: 

id attributes are intended to be unique. Try setting the class attribute to package-content and change your selector to .package-content instead of #package-content.

Ken Browning
+1  A: 

make package-content a class, you can still have id's on those divs but it is best-practice to make id's unique

<div id="container-div">
    <div id="package_1">
        <div>Package_1</div>
        <div id="pc1" class="package-content"></div>
    </div>
    <div id="package_2">
      <div>Package_2</div>
      <div id="pc2" class="package-content"></div>
    </div>
</div>

then use the class selector:

$(".package-content")
Jon Erickson