0

How would you change a attribute value when you're trying to initially set the attribute to a variable:

<div class="random" aria-expanded="false">
  ...
</div>

// setting the attribute value to variable `getAttrValue`
var getAttrValue = $('.random').attr("aria-expanded");


if ( getAttrValue == "false" ) {
  // try to set the aria-expanded to true
} else {
  // try to set the aria-expanded to false
}

I can do it like this:

if ( getAttrValue == false ) {
  $('.random').attr("aria-expanded", "true");
} else {
  $('.random').attr("aria-expanded", "false");
}

But I was trying to see if I can utilize the variable and shorten the coding

0

2 Answers 2

1

Store $('.random') as a variable to avoid repeated DOM queries. Each time you do $('.random'), jQuery searches the DOM for items that fit your selector. Instead, you can do it once and store it in a variable. Not only does it shorten your code, but it makes it run faster.

Because your attributes are going to be string values, you'll need to do a string comparison.

var $r = $(".random");
var getAttrValue = $r.attr("aria-expanded");
$r.attr("aria-expanded", getAttrValue=="false");

By using == (Equality Operator), the expression getAttrValue=="false" will evaluate to true or false.

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

3 Comments

I had to change the boolean to actual strings, if I did the ! logical NOT operator, is it supposed to know to switch between "true" and "false"? even though these boolean are actual strings?
If it just does getAttrValue=="false", how does it go back to "true"? is this supposed to toggle?
It will set it to the opposite of what it currently is. Think about it... x == "false" will return true if x is "false", and false if x is "true".
0
$('.random').attr("aria-expanded", getAttrValue == false);

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.