Thursday, January 8, 2009

How to select innermost element with jQuery

Today I was working on new category browser UI for the project I am working. I had to select the innermost element and append some more content into it. Basically, I had an HTML like this:

<div>Outermost element 
  <div>Some Text 
    <div>Evenmore text 
      <div>Who cares anymore? 
        <div>Innermost Element</div> 
      </div> 
    </div> 
  </div> 
</div>

So I needed to select the innermost div and append another div to it. There is no jQuery selector but you can use selectors that exist to achieve this goal. The innermost element would be the last div with the only-child.

$('div:only-child:last'); 

// Change background color to gray 
$('div:only-child:last').css('background-color',"#ccc");

2 comments:

  1. Hi Maujor,

    Yes it does fail, because the code snipped was not planned to be general innermost element selector.

    I was stressing more on how you can use MULTIPLE selector filters to achieve some goal. In this case using :only-child in combination with :last .

    ReplyDelete
  2. Hi,

    I want to get the src attribute value (the innermost child) using jquery, how?

    div>> child div >> child of child div>> img

    ReplyDelete