1
$(".focus-button").addClass('active');
$(".focus-button[data-expand='true']").addClass('active');

If I store the class selector in a variable like:

var btn = $(".focus-button");

The variable can be used in the code as

btn.addClass('active'); // This is correct
btn[data-expand='true'].addClass('active'); // This is wrong

May I know what is the right way to use variable with attributes.

1
  • 6
    filter api.jquery.com/filter btn.filter("[data-expand='true']") Commented Apr 19, 2017 at 8:51

4 Answers 4

3

You can use filter to add additional selectors in the way you want.

Reduce the set of matched elements to those that match the selector or pass the function's test.

Example:

var btn = $(".focus-button");
btn.addClass("active");
btn.filter("[data-expand='true']").removeClass("active")

Where

var btn = $(".focus-button");
btn.filter("[data-expand='true']")

is the same as

$(".focus-button[data-expand='true']")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info. have a Great day.
2

Situation:

In your actual code, if you write:

var btn = $(".focus-button");

You will get a collection of all elements with class focus-button, so when you write, btn.addClass('active'); it's correct and it will add the class active to all the elements in this collection.

Problem:

While when you write:

btn[data-expand='true'].addClass('active');

It's wrong because JavaScript will interpret it as you are accessing a property in your btn object, because [] are only used to access a specific property in an object or a specific element by index in an array.

And btn[data-expand='true'] is only a CSS selector.

Solution:

You can use jQuery .filter() as suggested in comments, like this:

btn.filter("[data-expand='true']").addClass('active');

1 Comment

Thanks for the answer. Have a Great day
1

try this snippet:

//$(".focus-button").addClass('active');
//$(".focus-button[data-expand='true']").addClass('active');


var btn = $(".focus-button");
//btn.addClass('active'); 

btn.filter("[data-expand='true']").addClass('active'); 
.active{
background: #000;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="focus-button">F</div>
<div class="focus-button" data-expand="true">E</div>

1 Comment

Thanks for the answer. Have a Great day
1

Try this code

btn.filter("data-expand='true'").addClass('active'); 

1 Comment

Thanks for the answer. Have a Great day

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.