This snipped is multiple times in my code, and i want to get user_id from the selected user
<li>
<div class="contact">
<div class="contact-name">James</div>
<p class="user_id">1234</p>
<div class="remove" onclick="remove()">Remove</div>
</div>
</li>
The code for jquery gets me an empty alert. I dont know what to change to get the user_id.
function remove() {
var id = $(this).parent().find('.user_id').text();
alert(id)
....
Does someone has an idea what i have to change?
>Solution :
onclick="remove()"
You should pass this into your function to reference the clicked element. By using this in your function, you are referencing to window scope.
function remove(clickedEl) {
var id = $(clickedEl).parent().find('.user_id').text();
console.log(id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>
<div class="contact">
<div class="contact-name">James</div>
<p class="user_id">1234</p>
<div class="remove" onclick="remove(this)">Remove</div>
</div>
</li>