How to get the ID value of the i tag?

Asked

Viewed 703 times

1

I have the following DIVS:

  <div id="img_btn2"><a href="#modal1" class="modal-trigger btn-flat"><i class="material-icons icone_branco">alarm</i></a></div>
  <div id="img_btn"><i id="img_lamp1" class="material-icons icone_branco">lightbulb_outline</i></div>
  <div id="nome_btn1" align="center">QUARTO</div>
  <div id="botoes" class="row" align="center">
      <div class="switch" align="center"><label>Desligado<input id="btn_cliente_on1" class="btn_onoff" value="http://192.168.10.102" type="checkbox"><span class="lever"></span>Ligado</label></div>
  </div>

And I want to get the tag ID i, via Jquery, but I’m not getting it via Closest.

$(document).on('click', '.btn_onoff', function(){ 
var id = $(this).attr('id');
var target = $(this).closest('i').attr('id');
var cmd = $(this).val(); 
console.log(target);
});

How to solve??

2 answers

2


The .Closest() in this case it is limited because you do not have a parent element of this whole HTML block. But you can use .Closest() with the .prevAll() thus:

$(document).on('click', '.btn_onoff', function() {
  var id = this.id;
  var target = $(this).closest('.row').prevAll('#img_btn').find('i').attr('id');
  var cmd = this.value;
  console.log(target, cmd, id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img_btn2"><a href="#modal1" class="modal-trigger btn-flat"><i class="material-icons icone_branco">alarm</i></a></div>
<div id="img_btn"><i id="img_lamp1" class="material-icons icone_branco">lightbulb_outline</i></div>
<div id="nome_btn1" align="center">QUARTO</div>
<div id="botoes" class="row" align="center">
  <div class="switch" align="center"><label>Desligado<input id="btn_cliente_on1" class="btn_onoff" value="http://192.168.10.102" type="checkbox"><span class="lever"></span>Ligado</label></div>
</div>

But if that i has ID and Ids can only be unique you could just do:

$(document).on('click', '.btn_onoff', function() {
  var id = this.id;
  var target = $('#img_btn').find('i').attr('id');
  var cmd = this.value;
  console.log(target);
});
  • 1

    Perfect!! Thanks for the quick reply!

  • 1

    @Guilhermelirio great to have helped.

1

The tag <i> sets a part of the text to display in italic.

It does not contain id, so it is not appropriate to make this logic.

My suggestion is that you separate with <div> and put the class with the same name for common elements, you will be able to retrieve the common information.

Elements <div> is able to use id

The tag <i> will do the following in your code:

i {
    font-style: italic;
}

Source: https://www.w3schools.com/tags/tag_i.asp

  • 1

    Um, well remembered, I didn’t touch it. Thank you for the reminder!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.