SpeedOfRound
SpeedOfRound

Reputation: 1278

Selecting nested elements

I have a page hierarchy like this:

<div class="panel" attribute-id="1">
  <button class="delete">
  <div class="panel" attribute-id="2" association-id="20">
    <button class="delete">
  </div>
</div>
....

So I have a bunch of these panels with nested panels inside, and I'm trying to create on on click handler for the delete buttons of the top level panels only (so the ones immediately inside panels that do not have an association id). The only different between the parent and child panels is that the child ones have the extra attribute "association-id".

So I can select the top level panels only like so:

$('.panel[attribute-id]:not([association-id]')

But if I try to get the delete buttons from from these like:

$('.panel[attribute-id]:not([association-id] .delete')

Obviously I'm still going to get the child buttons.

I can't modify the html in anyway, how could I go about doing this?

Upvotes: 0

Views: 81

Answers (3)

spaceman
spaceman

Reputation: 1167

$(':not(.panel[attribute-id][association-id]) > .delete')

seems to do the trick.

jsfiddle

I've changed .panel-group to .panel to get it to work with the HTML provided.

Upvotes: 3

Dan Weber
Dan Weber

Reputation: 1237

Wrap them all in a div and assign that div a unique class. Then you can use jquery selector ".panel-group > .panel" to get only direct children of top level.

<div class="panel-group">

 <div class="panel" attribute-id="1">
  <button class="delete">
  <div class="panel" attribute-id="2" association-id="20">
    <button class="delete">
  </div>
 </div>

 <div class="panel" attribute-id="11">
  <button class="delete">
  <div class="panel" attribute-id="12" association-id="120">
    <button class="delete">
  </div>
 </div>

</div>

Upvotes: 1

Akshay Shenoy
Akshay Shenoy

Reputation: 119

You can use the children method:

$('.panel-group[attribute-id]').children('button').first()

Upvotes: 0

Related Questions