JS: Setting focus on DOM-element does not update document.activeElement

Viewed 333

I'm currently trying to manually set focus on two buttons after each other. They are jQuery-Objects, saved in an array called pMenus. Here is the code

function OpenSubMenus(pMenus) {

    pMenus[pMenus.length - 1].get(0).focus();

    $(pMenus[pMenus.length - 1]).click();
    
    if (pMenus.length == 1) {
        return;
    }
    
    setTimeout(() => {
        pMenus[pMenus.length - 1].get(0).blur();
        pMenus.pop();
        OpenSubMenus(pMenus);
    }, 1000)
}

The problem is, that on the second manual .focus(), the activeElement stays on the body of the page. Has anyone encountered that problem before?

Thanks in advance.

2 Answers

Problem is that pMenus[pMenus.length - 1] returns second button not first. Use pMenus[pMenus.length - 2] to get first element.

Sorry, for bothering everyone. I did not provide enough information for you, as I should have mentioned, that the button to be focused was not not visible (visibility: hidden).

If the element is visible, the code mentioned in the question works.

Thanks for your help and have a good day.

Related