badsyntax badsyntax - 2 months ago 13
Javascript Question

jquery add class to element inside this element only

This is for a user account. When the user hits the edit button I want an edit box to be displayed inside the element where the button exists.

So I have this markup

<div class="col account">
<strong>Account Settings</strong>
<div class="col">
<span>Profile Status</span>
<p><?= $this->escape($this->status); ?></p>
<button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<div class="edit-box">
edit 1
</div>
</div>
<div class="col">
<span>Name</span>
<p> <?= $this->escape($this->name); ?></p>
<button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<div class="edit-box">
edit 2
</div>
</div>
<div class="col">
<span>Username</span>
<p><?= $this->escape($this->username); ?></p>
<button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<div class="edit-box">
edit 3
</div>
</div>
<div class="col">
<span>Bio</span>
<p><?= $this->escape($this->bio); ?></p>
<button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<div class="edit-box">
edit 4
</div>
</div>
<div class="col">
<span>Email</span>
<p><?= $this->escape($this->email); ?></p>
<button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<div class="edit-box">
edit 5
</div>
</div>
<div class="col">
<span>Password</span>
<p>**********</p>
<button class="edit-btn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<div class="edit-box">
edit 6
</div>
</div>
</div>
</div>


Then I have jquery

$(document).ready(function()
{
$('.edit-btn').click(function()
{
$('.edit-box').addClass('open');
});
});


Is there a way to add a class only to the .edit-box that lives in the same .col as the .edit-btn?

Here is a js fiddle https://jsfiddle.net/y6ukq3th/

Answer

Yes you can use .siblings('.edit-box') to add the class to the one who has that as a sibling of the clicked button:

$(document).ready(function() {
     $('.edit-btn').click(function() {
         $(this).siblings('.edit-box').addClass('open');
     });
 });

Demo