Home > Software design >  Why do i get an empty String from jquery find().text()?
Why do i get an empty String from jquery find().text()?

Time:05-02

This snipped is multiple times in my code, and i want to get user_id from the selected user

<li>
    <div >
        <div >James</div>
        <p >1234</p>
        <div  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?

CodePudding user response:

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 >
        <div >James</div>
        <p >1234</p>
        <div  onclick="remove(this)">Remove</div>
    </div>
</li>

CodePudding user response:

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.

  • Related