Home > Software design >  Javascript getAttribute not evaluating to string value in if statement
Javascript getAttribute not evaluating to string value in if statement

Time:11-05

I am trying to loop through the tabs on a page and figure out which one is selected (I am using a Tab container on oracle APEX) and the active tab has attribute aria-selected as true so I am looking for that.

I've tried the following code:

for (var i=0; i < document.getElementsByClassName('t-Tabs-link').length; i  ) {
    if (console.log(document.getElementsByClassName('t-Tabs-link')[i].getAttribute('aria-selected')) === 'true') {
        console.log('here');
    }
    else {
        console.log('not here');
    }
}

However, as you can see in the image below everything is evaluating to not true, even the tab that has the attribute as true. If someone could tell me what I am doing wrong I'd be very grateful.

Console Output

CodePudding user response:

use a forEach loop instead of for loop, its more clear and direct in its purpose

document.querySelectorAll('.t-Tabs-link').forEach(function(tab) {
    if (tab.getAttribute('aria-selected') === 'true') {
        console.log(tab.innerText, 'is selected');
    } else { console.log(tab.innerText, 'is not selected'); }
});
      <a  aria-selected="false">Tab 1</a>
      <a  aria-selected="false">Tab 2</a>
      <a  aria-selected="true">Tab 3</a>
   

CodePudding user response:

If you store the links in a variable it's easier to see what you're doing. You just had a couple typos in your for loop:

const tabsLinks = document.getElementsByClassName('t-Tabs-link');

for (var i = 0; i < tabsLinks.length; i  ) 
{
  if (tabsLinks[i].getAttribute('aria-selected') === 'true') 
  {
    console.log('here');
  } 
  else 
  {
    console.log('not here');
  }
}
<a  aria-selected="false">Tab 1</a>
<a  aria-selected="false">Tab 2</a>
<a  aria-selected="true">Tab 3</a>

  • Related