Efficient way to target the outer HTML element in jQuery

Given the HTML structure below. The goal is to modify the inner text of closest outer div tag with "log" class when an anchor tag is clicked. For example when the anchor tag with content "3a" is clicked, the div tag with "log" class inside the div wrapper with "content-a" class inner text should have a value of "3a clicked".

HTML:

  
<div class="content-wrapper content-a">
  <ul class="content-list">
    <li class="list"><a href="#">1a</a></li>
    <li class="list"><a href="#">2a</a></li>
    <li class="list"><a href="#">3a</a></li>
  </ul>
  <div class="log">Empty</div>
</div>
<div class="content-wrapper content-b">
  <ul class="content-list">
    <li class="list"><a href="#">1b</a></li>
    <li class="list"><a href="#">2b</a></li>
    <li class="list"><a href="#">3b</a></li>
  </ul>
  <div class="log">Empty</div>
</div>
  

The efficient way I found to accomplish this is to target closest parent and use the optional second parameter in jQuery() or $() called "context":

  
$('.content-list list a').click(function (e) {
  $parent = $(this).closest('.content-wrapper');
  $('.log', $parent).text($(this).text() + ' clicked'));
});
  

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.