Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading