Gary
Gary

Reputation: 4725

How do I know my selector is correct in jQuery

I have the following piece of HTML code:

<div class="myclass" id ="class1">
  <ol class="list">
     <li id="li_1">
         <input id="input_1" …>
         <acronym id="input_1" class="classabc">
      </li>
      <li id="li_2">
          <input id="input_2" …>
          <acronym id="input_2" class="classabc">
      </li>
        ....
      <li id="li_n">
          <input id="input_n" …>
          <acronym id="input_n" class="classabc">
      </li>
   </ol>
</div>

Now I want to change the class of some acronym tags, I have the id of an acronym tag, so I tried this:

$('acronym#'+id).removeClass('classabc');
$('acronym#'+id).addClass('newclass');

It didn't work so I tried:

$('div.myclass ol acronym#'+id).removeClass('classabc');
$('div.myclass ol acronym#'+id).addClass('newclass');

But it still doesn't work. I tried alert inside the code, the alert works. I am thinking my selector is not right. So I am asking is there anyway to get correct selector? Or how do I know my selector is correct?

Upvotes: 2

Views: 141

Answers (4)

Scruffy The Janitor
Scruffy The Janitor

Reputation: 472

It is not proper to have the same id declared for two elements.

Remove the id from acronym and then use the following javascript.

<input id="input_1">
<acronym class="classabc">

Where var id = "input_1";

$('#'+ id).siblings('acronym').removeClass('classabc');

The Fiddle

Here is a w3schools link to learning css selectors. http://www.w3schools.com/cssref/css_selectors.asp

Upvotes: 5

JW8
JW8

Reputation: 1506

The basic selector you'd be looking for should look something like this (since you have duplicate ids):

$('acronym[id='input_n'])

so you'd need to include the closing quotes:

$("acronym[id='input_" + n + "']")

Note: Since there are duplicate ids, this answer isn't using the more common $('#input_n') selector.

Upvotes: 2

devnull69
devnull69

Reputation: 16564

The key problem here: The id attribute MUST be unique for the document. You used the same id attribute several times and this will lead to no (or unpredictable) results using an id selector!

Upvotes: 2

ShankarSangoli
ShankarSangoli

Reputation: 69915

Ideally the id's on the page should be unique for every dom element. Considering that if you want to find any element by Id you can just use id selector. Try this

$('#'+id).removeClass('classabc');
$('#'+id).addClass('newclass');

Upvotes: 1

Related Questions