How to get the element id

Asked

Viewed 1,235 times

1

I have this HTML that has the id that is inserted in the loop...

<div class="item-total elemento" id = ${id}>

Therefore, I have this function:

$(document).on('touchstart', '.elemento', function (){

});

In this '.element' actually, I wanted to do something like '.elemento > id' of the element I clicked, remembering that this function is outside the loop of repetition... has some way of doing this?

  • I didn’t get it right, each of the div should perform a different function? so you want to do a loop by ID?

  • @h3nr1ke in reality no. He will do the same thing. Only then when I do it that way he applies it to everyone, and I just want him to do it in the target element.

  • Got it, so just use the $(this) within the function, for example, $(this).addClass("active");, only the clicked item will change, other items will not.

  • 1

    There’s no way to do it this way. The selector .elemento > id means selecting an item by class .elemento and a direct child with the tag id, only that there is no tag id. The sign > means child-direct.

  • @Sam I imagined. It was just to illustrate. But I thought I could do something like direct in function.

3 answers

2

In cases where you have several elements with the same class, but want to get the ID of the element that triggered the event, must use this (Pure Javascript) or $(this) (jQuery), in the example below I just changed the 'touchstart' event to 'click':

$(document).on('click', '.elemento', function (){
  console.log(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="item-total elemento" id ="1">1</div>
<div class="item-total elemento" id ="2">2</div>

  • I would like to apply in the function itself, for example: $(Document). on('click', '.element > id', Function(){ }); ?

  • You are wanting to select the id in the function, do not need this because you will already access it by this.

  • How do I want to apply $(Document). on('touchstart', '.element', Function(){ }); in the element id that would be the best way? am doing so because these html were inserted through the append.

1

An alternative way could be:

<div class="item-total elemento" id = ${id} onClick="funcao(this)">

Where soon after, in your Javascript file, your role should be written

function funcao(elemento) {
   // TODO
}

Providing the this as parameter allows you to retrieve field properties such as: this.value, this.id, etc

0

To interact with the event-enabled element only vc can

$(document).on('touchstart', '.elemento', function (){
    // adiciona uma class active apenas no elemento o selecionado
    $(this).addClass("active");

});

$(this) always make reference to the element that caused the event Trigger.

Browser other questions tagged

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