views:

59

answers:

6
+2  Q: 

jQuery selector

I have this HTML code:

<div class='com_box'>
  <div class='com_box_c'>
    <div class='com_box_info'>
      <a id='quote'>quote</a>
    </div>
  </div>
</div>

When I click in a#quote i want to add a textarea after '.com_box'.

How do I select the outer div? Here is my no working try so far:

$('a#quote').click(
  function() {
    var com_box = $(this).parent('div.com_box');
    com_box.after('<textarea>....</textarea>');
  }
)
+2  A: 

Use .closest()

Replace

var com_box = $(this).parent('div.com_box');

with

var com_box = $(this).closest('div.com_box');


$('#quote').click(
  function() {
    $(this).closest('div.com_box').after('<textarea>....</textarea>');
  }
)
rahul
+1  A: 

I don't think $(this).parent('div.com_box') will return any results, as parent only will return immediate parents. You probably just want $('div.com_box') for that (or $(this).closest('div.com_box')).

Jesse Millikan
+1  A: 

Use closest() as .com_box is not a direct parent of the #quote element:

$('a#quote').click(function() {
    var com_box = $(this).closest('div.com_box');
    com_box.after('<textarea>....</textarea>');
});

Using $(this).parent().parent().parent() would also work but that's what closest() is for. :)

Tatu Ulmanen
+1  A: 

Either:

var com_box = $(this).closest("div.com_box");

or

var com_box = $(this).parents("div.com_box:first");
cletus
It worked! Thanks :)
cvack
+1  A: 
$('#quote').bind('click' function() {
  $(this).parent().parent().parent().prepend('<textarea></textarea>');
});
Mark
A: 

var com_box = $(this).parent('div.com_box');

will not work but

var com_box = $(this).parents('div.com_box');

will work!

Take note the plural word is used: parents.

ilovewebdev