Dimitri Danilov
Dimitri Danilov

Reputation: 1352

why does my selector doesn't find my class?

My goal is to remove an image by clicking it.

I have this js:

    $('.imageSelected').on('click', function (event)
    {
        console.log('ok');
        $this.remove();
    });

And this html :

<li class="imageSelected">
  <a href="#">
    <div class="img-container" style="background-image:url({{ asset('bundles/mybundle/images/neige.jpg') }});">
     <div></div>
    </div>
  </a>   
</li>

But it never enters in my js, have any idea why ?

Upvotes: 0

Views: 52

Answers (4)

vrn53593
vrn53593

Reputation: 308

Given your code which has an javascript error which prevents you to display alert or run jquery further. However the issue in your code is $this instead the correct form of using it here is $(this) which resolves the issue. I have added modified code in the fiddle, So take a look at your code here.

*https://jsfiddle.net/raghucse2010/c4jjzhvw/7/*

Upvotes: 0

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

I think your elements are dynamically generated. You may need event delegation. Try like following.

$(document).on('click', '.imageSelected', function () {
    $(this).remove();
});

Upvotes: 1

Shyju
Shyju

Reputation: 218722

You should use $(this) or this to get the currently clicked item.

$(function(){

   $('.imageSelected').on('click', function (event){
        $(this).remove();
        // or this.remove();
    });

});

Here is a working sample.

When writing jQuery code, the value of this or $(this) variable will change based on the context/scope of your code. So it is always a good idea to assign your this to a local variable and use that for further things.

Example.

$(function(){

   $('.imageSelected').on('click', function (event){
        var _this=$(this);
        //Use _this as needed
        _this.css( { color : 'red' });

        $.post("UrlToDelete", { id :"someIdFromCurrentElement",function(res) {
                _this.fadeOut(100,function(){
                    _this.remove();
                });
        });

    });

});

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

As currently defined here, the $this is a new variable, which is undefined. You must use this to go to the current element. So, if you wanna use jQuery functions on them, you can wrap it like $(this).

Your solution would be:

$('.imageSelected').on('click', function(event) {
  console.log('ok');
  $(this).remove();
});

Upvotes: 2

Related Questions