R
R
RushV2021-07-01 12:29:44
JavaScript
RushV, 2021-07-01 12:29:44

How to check if id exists?

I welcome everyone!
There is a group id that starts with "submenu-1", "submenu-24", "submenu-32", etc.
How to write a check for these id s?
If there are such id then add the top class.

let subMenu = [...document.querySelectorAll($('#submenu-').click(function(){
        $(this).addClass('top');
        
    }))];

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-07-01
@sergiks

With the markup from the comment to the question, you can take all the links inside the common parent:

const sample = 'submenu-';
const links = [...document.querySelectorAll('ul.navbar-main a')]
  .filter((a) => a.id.startsWith(sample));
console.log(links); // массив со ссылками

links.forEach((a) => a.addEventListener('click', (e) => e.target.classList.add('top'));

upd. as Fedor Vlasenko well suggested in a comment , you can more elegantly use a selector that selects elements whose attribute begins with the specified string. a[id^=submenu]will select those anchor elements whose id starts with "submenu":
[...document.querySelectorAll('ul.navbar-main a[id^=submenu]')]
  .forEach((a) => a.addEventListener('click', (e) => e.target.classList.add('top'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question