Sachin Jain
Sachin Jain

Reputation: 21842

Jquery index() method to get index of child

I am using query index() method to get the index of an element relative to its parent.

Here are two codes : Code1

<div id="check1">
    <p>  
        <span> 
            <b> Bold Line 1 </b>
            <b> This is line2 </b>
        </span>
    </p>
    <p> Should have index 1 </p>
</div>

Code2

<div id="check2">
    <p>  
        <span> 
            <b> Bold Line 1 </b>
            **<p> This is line2 </p>**   //replaced <b> with <p>
        </span>
    </p>
    <p> Should have index 1 </p>
</div>

In code2, I just replaced the 2nd bold name with p tag name.

Area of doubt is answer varies in both these cases. Answers are:

Case1: index comes 1
Case2: index comes 3

Please check this out. "Click on Should have index 1" http://jsfiddle.net/blunderboy/U73VV/

And moreover, when I click on "This is line2" on both checks, their parents are coming different. In check1, parent is span and in check2 parent is div.

Please let me know what difference I am making just by changing the tagName. Their relative position w.r.t their parent is still same.

Upvotes: 2

Views: 194

Answers (2)

Alexander
Alexander

Reputation: 23537

You can't place <p/> tags inside <p/> tags. You are ending up with the following markup:

<div id="check2">
  <p>  
    <span> 
      <b> Bold Line 1 </b>
    </span>
  </p>
  <p> This is line2 </p>
  <p> Should have index 1 </p>
</div>

You might want to replace <b/> with a <span/> instead to keep the layout.

Or, if what you want is to change the bold attribute of the tags, you can use CSS for it. This won't need you to mess around with the layout.

.bold { text-weight: bold; }

Toggling the bold class:

<div id="check1">
  <p>  
    <span> 
      <!-- This is bold -->
      <span class="bold"> Bold Line 1 </span>
      <!-- This one is not bold -->
      <span> This is line2 </span>
    </span>
</p>
<p> Should have index 1 </p>

Upvotes: 3

albinohrn
albinohrn

Reputation: 626

It has to do with the ivalid markup. Your'e using nested <p>-tags wich isn't allowed. Changing case 2 to this, makes it work.

<div id="check2">
    <div>  
        <span> 
            <b> Bold Line 1 </b>
            **<p> This is line2 </p>**   //replaced <b> with <p>
        </span>
    </div>
    <p> Should have index 1 </p>
</div>

I don't know why it changes the index, but I do know that the markup is invalid.

Upvotes: 1

Related Questions