1

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 to 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
});

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I misread the jQuery docs on this one - docs.jquery.com/Selectors/id#id - clearly states it only selects one #id.
2

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")

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.