user16591216
user16591216

Reputation:

Why do i get an empty String from jquery find().text()?

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?

Upvotes: 0

Views: 161

Answers (2)

cheesyMan
cheesyMan

Reputation: 1510

You are using this in an erroneus way.

When you attach an eventListener like this:

$(element).on('click', function() {
   var id = $(this).parent().find('.user_id').text();
   alert(id)
}

the this will point to the target of the event, and you code will work.

BUT, you are executing your function with onclick=remove(), so it's a normal function call, and in this case this will be the global object (the window object as we're in a browser).

You can add a console.log(this) to your function clearly see that.

Upvotes: 1

Berkay Gumustekin
Berkay Gumustekin

Reputation: 46

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>

Upvotes: 3

Related Questions