Search code examples
jqueryvariablesjquery-selectors

How to select an element with attribute based on variable selector which is defined earlier?


var $label = $('label');

//How can I select a `label` using attribute selector, something like below.
$label['data-id=1'].text('some value');
//There is no such a syntax, I am just trying to explain what I need to do.

For more complete example, please visit this jsfiddle link


Solution

  • You can make use of filter to get the matching id label from $label and then set the text value. see below code

      var $label = $('label');
    
      var id = $(this).find('.form-control-data-id').text();
      var val = $(this).find('.form-control').val();
      $label.filter(function(){
        return id == $(this).data('id');
      }).text(val);
    

    JSFiddle Demo