0

Consider below HTML:

<div class="votingButton">
       <i class="icon-chevron-up"></i>
</div>

As you can see parent of i element is div, but when I try to get parent of i via jQuery it gives me i:

$(function () {
     $('.icon-chevron-up').on('click', function () {
        alert($(this).parent().html());
     });
 });

Above code gives me <i class="icon-chevron-up"></i>, I also tried these cases:

$(this).closest('.votingButton').html()
$(this).parents().html()
$(this).parents('.votingButton').html()

But still get <i class="icon-chevron-up"></i>
Any idea?

Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110

3 Answers3

2

Of course it does. You're using .parent().html(). The HTML of the parent of your .icon-chevron-up element is:

<i class="icon-chevron-up"></i>

If you modified your HTML to:

<div class="votingButton">
    <i class="icon-chevron-up"></i>
    <span>Hello, world!</span>
</div>

The result of $(this).parent().html() would be:

<i class="icon-chevron-up"></i>
<span>Hello, world!</span>
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

The .html of the div class="votingButton" is

 <i class="icon-chevron-up"></i>

If you try to change the html() you might understand better. Try:

 $(function () {
      $('.icon-chevron-up').on('click', function () {
          $(this).parent().html("Removing the icon since that's the actual content of the parents div");
     });
 });
user2687506
  • 789
  • 6
  • 21
0

try this (UPDATED AND TESTED) :

$(function () {
     $('.icon-chevron-up').on('click', function () {
        alert($(this).parent().wrap('<p/>').parent().html());
         $(this).parent().unwrap();
     });
 });

this will give you the html code of the parent (and its children inside it)

Youness
  • 1,468
  • 1
  • 9
  • 19
  • This will return *undefined*, as jQuery's returning `parent()` object has no `outerHTML` property. You'd need to use `parent()[0].outerHTML` instead. The question of how to get an element's outer HTML has been asked many times and already has a highly upvoted answer here: http://stackoverflow.com/a/4741203/1317805 - this answer also states why the `outerHTML` property should not be used. – James Donnelly Aug 07 '14 at 08:40