sam4od
sam4od

Reputation: 3

target looped html attributes singularly

I'm actually finding it difficult to get the element attribute am targeting on click.

i built an auto search system and also i want to add a feature of delete..

after result is droped down as a looped element, i want to be able to click on a particular element delete button and be able to delete that from the database using its element data-id="each-number" , how can i target the attribute with JavaScript only for the particular element ignoring others

static delApi(delClassName, attribute){
      const del = document.querySelectorAll(delClassName);
      del.forEach(e =>{ 

      })

static delApi(delClassName, attribute){
      const del = document.querySelectorAll(delClassName);
      del.forEach(e =>{ 
           e.target.this.attribute //only
      })

Image

Upvotes: 0

Views: 33

Answers (1)

David784
David784

Reputation: 7464

I don't understand your code snippet at all; forEach has nothing to do with click event handlers. But your notion of e.target is actually pretty close. Here is an example of how that would work in the context of an event listener callback.

I'm using vanilla JavaScript with the addEventListener, because while you included the jQuery tag, all of your code above is vanilla. I'm also creating a single event listener and allowing the click event to bubble, and then I'm filtering out any events I might not be interested in.

All of this is a little more straightforward with jQuery, since it can handle all the filtering for you: e.g. $(document.body).on('button', function(e) { /* ... */ }).

I'm able to pull from the data-id attributes using dataset.

document.body.addEventListener('click', function(e) {
  if(e.target.tagName==='BUTTON') console.log("delete", e.target.dataset.id);
});
<button data-id="1">one</button>
<button data-id="2">two</button>
<button data-id="3">three</button>
<button data-id="4">four</button>

Upvotes: 2

Related Questions