1

How can I remove this parent div by data attribute when you click X, as you see data-userid changeable. Maybe it should be like this $('.delete').find("[data-userid='" + userId + "']") , userId refer to the number.

<div>
    Just Test
    <a class="delete" href="#" data-userid="5">X</a> 
</div>
<div>
    Just Test
    <a class="delete" href="#" data-userid="6">X</a> 
</div>
1
  • use remove() function Commented Apr 30, 2016 at 23:33

5 Answers 5

2

.find() will look for a child of the element you selected with $('.delete'). Instead, directly select the a with the data attribute that you want, then reach up to find its parent.

var userId = 5;
var link = $('.delete[data-userid="' + userId + '"]');
var parent = link.parent();

Now you can remove the whole div like this:

parent.remove();

http://codepen.io/anon/pen/BKGopr

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to delete the parent div, you should use the parent selector like this:

$('.delete[data-userid="' + userId + '"]').parent('div').remove();

I read in your question that you want to delete the parent div of the a clicked, so you can do this too:

$("a.delete").click(function(){
  $(this).parent('div').remove();
});

I hope my answer help you.

Comments

0

Here we go: remove() function can help you! Here is an example:

jQuery:

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").remove();
    });
});
</scrpt>

HTML:

<div id="div1">

This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>
<br>

<button>Remove div element</button>

Hope it helps;)

Comments

0

If you want to delete the element for all user then you can just add id to your element and delete it using $("#id").remove(); but if you want to delete based on any specific user then you can use data attribute to find the element and delete it.

Comments

0

this should do the trick

$('.delete').on('click',function(){
        //$(this).parent().remove();
        $(this).parent().hide();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.