user800426
user800426

Reputation: 183

Matching when element has multiple ids

I'm looping through a form and showing content that matches my selected id's. The problem is that some divs contain more than one id in which case it stops working. Any ideas? Thanks.

Jquery Code:

$('#myForm').find('div').each(function() {
        var myId = $(this).attr('id');

        /* This will work */
        if (myId == "Select1"){
                $(this).removeClass("hideMe");
                $(this).addClass("showMe");
                }
        /* This does not work */
        else if (myId == "Select4"){
                $(this).removeClass("hideMe");
                $(this).addClass("showMe");
                }
        else{}

        }); 

HTML Code:

<div class="hideMe" id="Select1">
<p>Some Content</p>
</div>

<div class="hideMe" id="Select2 Select3 Select4 Select5">
<p>Some Content</p>
</div>

Upvotes: 4

Views: 1379

Answers (5)

Chris Baker
Chris Baker

Reputation: 50592

There is no such thing as "multiple ids".

https://developer.mozilla.org/en/XUL/Attribute/id

According to the standard, any string data within the id property is regarded as a part of the value.

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

reference: http://www.w3.org/TR/REC-html40/types.html#type-name

There's another way, though! You can have all sorts of class names, and you can use jQuery to grab an element by class name.

HTML

<div class="hideMe Select1">
<p>Some Content</p>
</div>

<div class="hideMe Select2 Select3 Select4 Select5">
<p>Some Content</p>
</div>

Javascript

$('.Select2')[0]

The [0] part of that is because when you get elements by class name, there can be several. The jQuery selector returns an array, so you're just grabbing the first one.

Upvotes: 10

patapizza
patapizza

Reputation: 2398

An element shouldn't have more than one unique identifier that's why it's actually called an id: to identify it against all others. Anyway, you have to test if myId contains Select4 rather than testing the equality.

Upvotes: 0

Marko
Marko

Reputation: 72222

ID's are unique and elements can only have 1 ID!

Use multiple classes instead.

Upvotes: 0

Ben Hull
Ben Hull

Reputation: 7673

It's not valid to have multiple ID's - the browser will see id="Select2 Select3 Select4 Select5" as a single string, but that string will be invalid because it contains spaces.

From the HTML data types spec: http://www.w3.org/TR/REC-html40/types.html#type-name

You should use classes for this, I think.

Upvotes: 1

Jason
Jason

Reputation: 52523

You can't have multiple ids. However, you can have multiple classes if you wish.

Upvotes: 1

Related Questions