Search code examples
javascriptjquerycsscustom-data-attribute

Select element based on data attribute


I have the following html and I am trying to add a class to it via the data attribute:

<p class="form-row form-row-wide" data-child-field="child_has_jacket">
</p>

Using jquery I've tried :

jQuery(document).ready(function( $ ){
       $('.form-row [data-child-field='child_has_jacket']').addClass("selected");
  });

Doesnt work. Anyone an idea?


Solution

    1. Use $('.form-row[data-child-field=child_has_jacket]').addClass("selected");. Check space is removed after .form-row other wise it will start searching for child element with that data attribute.

    2. Missing ; in CSS around height and display

    Working snippet:

    jQuery(document).ready(function( $ ){
       $('.form-row[data-child-field=child_has_jacket]').addClass("selected");
    });
    
    /*Other working snippets
    jQuery(document).ready(function( $ ){
       $('.form-row[data-child-field="child_has_jacket"]').addClass("selected");
    });
    
    jQuery(document).ready(function( $ ){
       $(".form-row[data-child-field='child_has_jacket']").addClass("selected");
    });*/
    .form-row.selected {
      border:1px solid black;
      width:20px;
      height:20px;
      display:block;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p class="form-row form-row-wide" data-child-field="child_has_jacket">
    </p>

    Other working snippets:

    jQuery(document).ready(function( $ ){
       $('.form-row[data-child-field="child_has_jacket"]').addClass("selected");
    });
    
    jQuery(document).ready(function( $ ){
       $(".form-row[data-child-field='child_has_jacket']").addClass("selected");
    });