Possible causes of errors:
Library is missing
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Code in the wrong position. (in your case it is correct, under the button)
See your code working:
$('.btn-remove').click(function(){
let id = $(this).attr('data-id');
console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html> <head> <meta charset="utf-8"> </head>
<body>
<h1>Teste de button</h1>
<button class="btn-remove" data-id='2'>Deletar</button>
</body>
</html>
The correct order is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html> <head> <meta charset="utf-8"> </head>
<body>
<h1>Teste de button</h1>
<button class="btn-remove" data-id='2'>Deletar</button>
</body>
</html>
<script language="javascript">
$('.btn-remove').click(function(){
let id = $(this).attr('data-id');
});
</script>
or with $( Document ).ready()
Code included within $( document ).ready()
will only be executed once the Document Object Model (DOM) page is ready to execute Javascript code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$('.btn-remove').click(function(){
let id = $(this).attr('data-id');
});
});
</script>
<html> <head> <meta charset="utf-8"> </head>
<body>
<h1>Teste de button</h1>
<button class="btn-remove" data-id='2'>Deletar</button>
</body>
</html>
Do you have jQuery code being imported into your HTML? This is a classic file error that is not being imported.
– João Pedro Schmitz
I have no friend, only the <script></script>
– A. Silva
if the answer is correct mark as accepted, see https://i.stack.Imgur.com/evLUR.png
– user60252