开发者

jQuery selector: How do I select the outer div?

开发者 https://www.devze.com 2022-12-21 20:36 出处:网络
I have this HTML开发者_JS百科 code: <div class=\'com_box\'> <div class=\'com_box_c\'> <div class=\'com_box_info\'>

I have this HTML开发者_JS百科 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>');
  }
)


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>');
  }
)


Either:

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

or

var com_box = $(this).parents("div.com_box:first");


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')).


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. :)


$('#quote').bind('click' function() {
  $(this).parent().parent().parent().prepend('<textarea></textarea>');
});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消