1

How to traverse the DOM and push all the focusable elements to an array dynamically using JavaScript ?

Say for example my markup looks something like this

Shark World

The world's leading source on shark related information.

Types of Sharks

I tried the sloution but then it's not working and newArray length is always 0:

let newArray = [];
const focusableElements = Array.from(document.body.children).filter(getFilteredElements);
function getFilteredElements(i){        
    if(i.localName !== 'script'  && i.attributes[0].value == 1){   
        newArray.push[i.localName]; 
    }
    return newArray;
}

console.log(focusableElements);

//length of new array is always 0 though if condition is getting executed and and the values are being push to "newArray".

Naina
  • 21
  • 2
  • This is the absolute stupidity of Stack Overflow rushing to close questions. How in the world is this question (about plain vanilla Javascript) answered by another that asks how to do the same thing with a third-party library (JQuery)? – webstackdev Jan 31 '23 at 21:15

1 Answers1

1

https://stackoverflow.com/a/36410810/7616528

var focusableElements = document.querySelectorAll([
  'a[href]',
  'area[href]',
  'button',
  'details',
  'input',
  'iframe',
  'select',
  'textarea',
  '[contentEditable=""]',
  '[contentEditable="true"]',
  '[contentEditable="TRUE"]',
  '[tabindex]:not([tabindex^="-"])',
  ':not([disabled])'
].join(','));
TheMisir
  • 4,083
  • 1
  • 27
  • 37