Convert string to boolean and toggle it?

I know there are longer ways of doing this, but I have an attribute on a button (aria-expanded) and I’m trying to convert that string to a boolean and then have it toggle from false to true, and vice versa.

 console.log(!(!! $(this).find(".nav-toggle").attr("aria-expanded")));
  $(this).find(".nav-toggle").attr("aria-expanded",  !! !$(this).find(".nav-toggle").attr("aria-expanded"));

I’m just looking for a more concise way of doing this without having to do a more longform version. Am I missing something obvious?

What if you evaluate the string value inside your attr method? Will this suffice?

  const $navToggle = $(this).find(".nav-toggle");
  $navToggle.attr("aria-expanded", $navToggle.attr("aria-expanded") === "true");
2 Likes

Is the aria-expanded a string, or a number?
!(!!string) doesn’t work; or rather, it evaluates anything that isnt the empty string as true. (“false” is truthy.)

Mateus’ code is probably the closest you’ll get, except it needs to negate the condition: if “true”, it needs to evaluate as false.

Alternatively: !Boolean($navToggle.attr("aria-expanded"))

1 Like

Naa, "false" will still evaluate to true.

1 Like

Oh good catch. Hmm. Could have sworn MDN said it wouldnt. Oh well. Stick with Mateus’ then, with a !== instead of ===.

1 Like

(Only caught because I was going to suggest that too LOL.)

1 Like

Not gonna lie. new Boolean was the first thing I was gonna suggest too. :laughing:

1 Like

String, sorry. Aria-expanded can be true or false.

<button aria-expanded="false">Text</button>

@Mateus 's suggestion worked beautifully (with @m_hutley 's suggestion of !== instead of ===)

Thank you :slight_smile: .

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.