I'm trying to use jQuery to select a div element but, for the life of me I can't figure out how to get it to work. I'm trying to set it up so when the user clicks on the span
element with the class remove
it finds the closest div
element with the class class-i-want-to-select
This block of code is dynamically added after the page has finished loading:
<div class="container">
<div>
<span style="float:left;">some text</span>
<span class="remove" style="float:right;">[X]</span> ///user clicks here
</div>
<div style="clear:both;"></div>
<div class="class-i-want-to-select"></div> ///want to select this element
</div>
This is the code i tried to use:
$('body').on('click', '.remove', function () {
var that = $(this).closest('div').find('.class-i-want-to-select');
console.log(that);
});
I figured the code above would properly select the element I'm trying the select but it's not working. Am I doing something wrong? Since the code block I'm traversing is dynamically added, is there a different way I need to select it?
Try this: you are trying to get closest div and then finding class which will not give you the parent div having class class-i...
You need to put class selector .container
in closest
only and it will return the correct parent div, then call find
on it to get class-i-want-to-select
. check below code
$(document).on('click', '.remove', function () {
var $parent = $(this).closest('div.container');
var that = $parent.find('div.class-i-want-to-select');
console.log(that);
});