Home > database >  get element by data attribute
get element by data attribute

Time:12-10

I have this html structure:

<table id="table">
   <tr data-id="3">
      <td>08.09.2021</td>
      <td><div >Delete</div></td>
   </tr>
</table>

and this onclick function:

var myID = 3;
$(".btnDelete").click(function() {
    
   console.log(
      $('#table').parents('tr').find("[data-id='"   myID   "']").html()
   )

})

Result will be "undefined". I would like to get the html part of <tr data-id="3"> and search this element by the data attribute "data-id". But my way doesn't work.

Where is my mistake?

CodePudding user response:

Here is your error:

  $('#table').parents('tr').find("[data-id='"   myID   "']").html()

That should be:

  $('#table').find("[data-id='"   myID   "']").html()

CodePudding user response:

The element with the id table doesn't have any ancestors (the parents function searches for ancestors not just parents) that are tr elements in the HTML you've provided.

Get rid of that clause.

  • Related