How do I get the value of the i-tag ID?

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 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 ??

    
asked by anonymous 15.06.2017 / 21:48

2 answers

2

The .closest () in this case is limited because you do not have a parent element of this entire HTML block. But you can use .closest () with .prevAll () like this:

$(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><divid="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);
});
    
15.06.2017 / 22:01
1

The <i> tag defines a portion of the text for display in italic .

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

My suggestion is to separate with <div> and put class with the same name for common elements, so you can retrieve the common information.

Elements <div> is able to use id

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

i {
    font-style: italic;
}

Source: link

    
15.06.2017 / 22:02