0

I have a button which has an ID, on click of the button I need to match the ID of the button with the documents data-id attribute and then add a class to the respective element.

JS Fiddle

this.$('.add-resource').click(function() {
  var testId = $(this).attr('id');
  alert(testId);
  $('#layoutCanvas').find("[data-id='" + testId + "']").addClass('hidden');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="btn btn-primary add-resource" id="567">Button</a>
<div id="layoutCanvas">
  <div data-id="567">
    Test 1
  </div>

  <div data-id="235">
    Test 2
  </div>
</div>

1
  • 2
    your code is working fine Commented Jan 28, 2019 at 9:18

3 Answers 3

4

Your .hidden class is not defined, so the class is added, but no css is applied.

I've only added the .hidden class

this.$('.add-resource').click(function () {
     var testId = $(this).attr('id');
     //alert(testId);
     $('#layoutCanvas').find("[data-id='" + testId + "']").addClass('hidden');
});
.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-primary add-resource" id="567">Button</button>


<div id="layoutCanvas">
    <div data-id="567">
        Test 1
    </div>
    
    <div data-id="235">
        Test 2
    </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

Well to modify a bit you can use template literals to overcome the dirtiness of string concat,its just a add on

this.$('.add-resource').click(function () {
     var testId = $(this).attr('id');
     //alert(testId);
   $("#layoutCanvas").find(`[data-id='${testId}']`).addClass('hidden')
     
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<a class="btn btn-primary add-resource" id="567">Button</a>
<div id="layoutCanvas">
    <div data-id="567">
        Test 1
    </div>
    
    <div data-id="235">
        Test 2
    </div>
</div>

<style>
.hidden{
  //attribute you want to add
 
}
</style>

Comments

0

hide() method hides the selected elements in jQuery :

this.$('.add-resource').click(function () {
     var testId = $(this).attr('id');
     alert(testId);
     $('#layoutCanvas').find("[data-id='" + testId + "']").hide();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.