Search code examples
jqueryjquery-selectorsthisparentclosest

jQuery: Click select Previous / Closest div with selector


I’ve being sitting for some while trying to solve a issue which I’m certain is quite simple but it just can’t get it to work.

I got this HTML:

<div class="span4">
    <div id="content" class="col-1"></div>
  <div class="add">
    <div class="dropdown btn-group">
        <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
            Add element
            <span class="caret"></span>
        </a>
        <ul class="dropdown-menu" id="addToColumn" data-col="1">
            <li><a href="#" id="headline">Headline</a></li>
            <li><a href="#" id="file">File</a></li>
            <li><a href="#" id="linebreak">Linebreak</a></li>
        </ul>
    </div>
  </div>
</div>

this is wrapped inside a div (class=row) which is again wrapped inside another div (class=container).

Now, when I press either of the three links (Headline, File or Linebreak) I have some JS to do some ajax and then insert some content in the empty div content.

But for the life of me I just can’t select the div.

I should mention, that the block of code is repeated three times, so I have three columns which each contain same dropdown menu with same three links and I want to make it as flexible as possible (before I used some different data-? attributes, but I want to use as few of those if possible).

My JS code looks something like this right now:

$("#addToColumn li a").click(function() {
    var elementType = $(this).attr('id');

// I’ve tried this but with no luck:
var col = $(this).closest("div#content");
    // AND
    var col = $(this).prev("div#content");
}

There are something which confuses me with this DOM tree. I want want each of the dropdown menus to insert something in the right wrapper-div for the right column and I want to try to do it without the use of some numeric “ID’s” but just select the “closest” content div and insert the data in this.

How do I go about doing that?

Any help if very appreciated

-Cheers


Solution

  • You can only have 1 element having id="content". having more than one is invalid and can cause unexpected behaviour. the rest of the code seems about right. if you change your id to class the following should work: var col = $(this).parents(".row").find(".content");. Same goes for id="addToColumn", id is meant to be unique - use classes instead.