hellomello
hellomello

Reputation: 8597

jQuery: Change an attribute value through variable

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

Upvotes: 0

Views: 91

Answers (2)

Tyler Roper
Tyler Roper

Reputation: 21672

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.

Upvotes: 1

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

Upvotes: 0

Related Questions