Identifying clicked elements I'm relatively new to web development. I started learning JavaScript a few months ago and it's going well. I made this code for someone on fiverr, and it got the job done, but I know there's a more efficient way to write this without using a click handler for each element. There has to be a way to know which element is clicked and show the proper one without a separate click handler for each element. 

Here's the Codepen link to the code.



HTML

&lt;div&gt;
  &lt;a href="#" id="item-1"&gt;Item 1&lt;/a&gt;
  &lt;a href="#" id="item-2"&gt;Item 2&lt;/a&gt;
  &lt;a href="#" id="item-3"&gt;Item 3&lt;/a&gt;
  &lt;a href="#" id="item-4"&gt;Item 4&lt;/a&gt;
&lt;/div&gt;
&lt;div class="item-container"&gt;
  &lt;div class="item-block" id="1"&gt;
      &lt;h1&gt;Item 1&lt;/h1&gt;
      &lt;p&gt;This is Item 1 content&lt;/p&gt;
  &lt;/div&gt;
  &lt;div class="item-block" id="2"&gt;
    &lt;h1&gt;Item 2&lt;/h1&gt;
    &lt;p&gt;This is item 2 content&lt;/p&gt;
  &lt;/div&gt;
  &lt;div class="item-block" id="3"&gt;
    &lt;h1&gt;Item 3&lt;/h1&gt;
    &lt;p&gt;This is item 3 content&lt;/p&gt;
  &lt;/div&gt;
  &lt;div class="item-block" id="4"&gt;
    &lt;h1&gt;Item 4&lt;/h1&gt;
    &lt;p&gt;This is item 4 content&lt;/p&gt;
  &lt;/div&gt;
&lt;/div&gt;


CSS



.item-block {
  display: none;
}


JS



$(document).ready(function() {
  $('#1').show();
})

$('#item-1').click(function() {
  $('.item-block').hide();
  $('#1').show();
})

$('#item-2').click(function() {
  $('.item-block').hide();
  $('#2').show();
})

$('#item-3').click(function() {
  $('.item-block').hide();
  $('#3').show();
})

$('#item-4').click(function() {
  $('.item-block').hide();
  $('#4').show();
})
In the HTML, give some id to your div with links, like this:

&lt;div id="links"&gt;
  &lt;a href="#" id="item-1"&gt;Item 1&lt;/a&gt;
  &lt;a href="#" id="item-2"&gt;Item 2&lt;/a&gt;
  &lt;a href="#" id="item-3"&gt;Item 3&lt;/a&gt;
  &lt;a href="#" id="item-4"&gt;Item 4&lt;/a&gt;
&lt;/div&gt;


Then change your JavaScript like this:

$("#links &gt; a").click(function(){
   $('.item-block').hide();
   $("#"+this.id.replace("item-","")).show();
})