Take the value of an HTML id with Jquery

2

Something I have to be doing wrong but I do not see what. I have a list of divs and I want them to click on an item in the list to take their id. I currently have this but I can not get it to work.

(function($) {

  function selectParams() {
    $(this).click(function(){
      var id = $(this).attr("id");
      console.log(id);
    });
  }
})(jQuery);
      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-column" id="first-column">
  <li id="WE"><div><span>WERK</span></div></li>
  <li id="OU"><div><span>OUTER</span></div></li>
  <li id="IN"><div><span>INTRA</span></div></li>
</div>
    
asked by Findelias 21.02.2018 в 16:15
source

2 answers

4

What happens is that the click event selector is wrong. You have it in this but what you should put is the element in which the event is specified, it should be in the li element:

$("li").click(function() {
  var id = $(this).attr("id");
  var name = $(this).closest("li").prop("tagName");
  console.log(id+": "+name);
  console.log();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-column" id="first-column">
  <li id="WE">
    <div><span>WERK</span></div>
  </li>
  <li id="OU">
    <div><span>OUTER</span></div>
  </li>
  <li id="IN">
    <div><span>INTRA</span></div>
  </li>
</div>
    
answered by 21.02.2018 / 16:23
source
0

(function($) {
  $('.first-column li').click(function(){
    console.log($(this).attr('id'));
  });
});
<div class="first-column" id="first-column">
                            <li id="WE"><div><span>WERK</span></div></li>
                            <li id="OU"><div><span>OUTER</span></div></li>
                            <li id="IN"><div><span>INTRA</span></div></li>
                        </div>
    
answered by 21.02.2018 в 16:23