Search code examples
javascriptjqueryhtmlthis

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 can 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 which 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);
    });
});

Solution

  • Your selector in has() is missing the . prefix for the class. You also need to check the length property of the resulting jQuery object. Try this:

    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);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <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>