0

I have a header in my html that has two different classes. Depending on when I scroll down it changes. IN CSS u select descendent with space. In my case .navbar .menu-toggler and .nav_sticky .menu-toggler. I succeded to select .navbar via var h = document.getElementsByClassName(id3)[0]; (id3 being "navbar") but i want to change the style of .menu-toggler And i can't write directly .menu-toggler because i need it when it's withing the class of .navbar .I over complicated the explanation but I hope somebody can help

oH and how can i add a class and remove a class to an element

double-beep
  • 5,031
  • 17
  • 33
  • 41
  • Have you tried css selectors such as ">" (or just look at [this question](https://stackoverflow.com/questions/632100/apply-css-style-to-child-elements))? – MefAldemisov Dec 20 '20 at 10:16
  • Welcome to Stack Overflow! Please do not edit solution announcements into the question. Create yourself an answer instead or accept one of the existing answers. – Yunnosch Dec 20 '20 at 11:49
  • You can add or remove classes using element.classList.add('classToBeAdded') and element.classList.remove('classToBeRemoved') – Dorin Baba Dec 20 '20 at 12:22
  • You've tagged the question "jquery". The jQuery way of adding/removing classes is with the `addClass` and `removeClass` methods. For example: `$('#my-element-id').removeClass('a-class')`. – David Knipe Dec 20 '20 at 12:45

1 Answers1

0

I guess you can use document.querySelector to access the toggler.

var menuToggler = document.querySelector(".navbar.menu-toggler");

You'll get the item which has .navbar and .menu-toggler inside it's classList.

I don't thing accessing children by indexes is a good practice. If your HTML document gets updated, your index might point to another DOM element.

Check this answer for more information https://stackoverflow.com/a/59406548/9517443

Dorin Baba
  • 1,578
  • 1
  • 11
  • 23
  • seems like a really good answer although it doesn't resolve my problem.. I have ` – Gulyasy Alex Dec 20 '20 at 11:23
  • function `toggle_visibility(id3) { var menuToggler = document.querySelector(".navbar.menu-toggler"); if(e.style.left == '0px'){ //e is header// deleted that part menuToggler.style.left = '240px'; } else{ menuToggler.style.left = '15px'; }` Basically i want the button to move itself to the left – Gulyasy Alex Dec 20 '20 at 11:24
  • I think I got it. You have something with class ".navbar" which contains a button with class ".menu-toggler". In this case you can use the following snippet: `button = document.querySelector('.navbar').querySelector('.menu-toggler');` Give it a try. – Dorin Baba Dec 20 '20 at 11:35