Robin B Robin B - 3 months ago 7
HTML Question

jQuery on click to check if it has a div with a certain class and then change the value of a different class

The code that i am writing is for an application where you select an icon and you get the css line displayed so you easily copy paste it and use it for another project. I'm having trouble with the $(this) selector. I have several divs with the "glyph-holder" class and it doesn't matter wich one I press, it always changes the "copy_text" div's value to the same class, the first one. I want it to change it to the div that i pressed.

The html that i have is:

<div id="copy_text">Select icon</div>
<div class="glyph-holder">
<div class="glyph">
<div class="icon-flip-horizontal"></div>
</div>
<div class="beschrijving-bij-glyph">
icon-flip-horizontal
</div>
</div>


The javascript that i currently have is this:

$(document).ready(function(){

var displayText = "Empty";

$(".glyph-holder").click(function(){

if($(this).has("icon-flip-horizontal")){
displayText = "icon-flip-horizontal";
}else if($(this).has("icon-flip-vertical")){
displayText = "icon-flip-vertical";
}

$("#copy_text").text(displayText);
});
});

Answer

You're not currently specifying that the has is looking for a class, also .has() returns a jQuery object and therefore .length should be used to test for the number of elements. Try this instead.

$(document).ready(function(){

    var displayText = "Empty";

    $(".glyph-holder").click(function(){

        if($(this).has(".icon-flip-horizontal").length){
            displayText = "icon-flip-horizontal";
        }else if($(this).has(".icon-flip-vertical").length){
            displayText = "icon-flip-vertical";
        }

        $("#copy_text").text(displayText);
    });
});

Note, the . in .has(".icon-flip-horizontal") is important since it's referencing a class.

Comments