lipenco
lipenco

Reputation: 1368

adding class to a sibling on clicking on nested element

I have a problem with dom-manipulation. I would like to add class to .text element on click on .fonts-container li.

<div class="editor">
    <h2 class="text">Heading</h2>
    <div class="ui-resizable-handle"></div>
    <div class="ui-resizable-handle"></div>
    <div class="ui-resizable-handle"></div>
    <img class="icon-layer-up2" >
    <img class="icon-layer-down2">
    <img class="icon-trash2">
    <i class="icon-move"></i>
    <i class="font2"></i>
    <div class="fonts-container">
        <ul>
            <li data-fontname="Aclonica">Aclonica</li>
            <li data-fontname="Acme">Acme</li>
            <li data-fontname="Alegreya">Alegreya</li>
        </ul>
    </div>
</div>

here is my buggy JS:

$(document).on('click', '.fonts-container ul li', function(){ 
    if ( $('.font2').hasClass("active")) {
        var fontName = $(this).data("fontname");
        $(this).prev().parent(".editor").find('.text').addClass("fontset");
    }
});

Upvotes: 2

Views: 1077

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173542

You can go up the tree until you reach .fonts-container by using .closest() and then find the sibling node using .siblings():

$(this).closest('.fonts-container').siblings('.text')

Upvotes: 1

Neeraj
Neeraj

Reputation: 4489

Use parents

$('li'.'.fonts-container').on('click', function(){
 if ( $('.font2').hasClass("active")) {
  var fontName = $(this).data("fontname");
  $(this).parents(".editor").find('.text').addClass("fontset");
 }
});

Upvotes: 0

naveen goyal
naveen goyal

Reputation: 4629

use parents

$(document).on('click', '.fonts-container ul li', function(){
     if ( $('.font2').hasClass("active")) {alert('a');
      var fontName = $(this).data("fontname");
      $(this).parents(".editor").find('.text').addClass("fontset");
     }
});

Upvotes: 0

Rituraj ratan
Rituraj ratan

Reputation: 10378

use closest

$(document).on('click', '.fonts-container ul li', function(){ 
     if ( $('.font2').hasClass("active")) {
      var fontName = $(this).data("fontname");
      $(this).closest(".editor").find('.text').addClass("fontset");
     }
});

Upvotes: 1

Related Questions