0

I want to get with querySelector method an element with pseudoclass ::before, How can i do this in vanilla Js? This is my attempt:

const menuDropdown = document.querySelectorAll('[class$="menu-dropdown"');
const about = document.querySelector('#about');

about.addEventListener('mouseover', function () {

    for(let el of menuDropdown) {
        console.log(el);
        el.style.opacity = '1';
        el.style.visibility = 'visible';
    }

})
.menu-dropdown:before {
    content: '';
    position: absolute;
    background-color: black;
    display: block;
    top: -15px;
    left: 50%;
    transform: translateX(-50%) rotate(45deg);
    height: 30px;
    width: 30px;
    opacity: 0;
    visibility: hidden;
}
<div id="about">
  <ul class="menu-dropdown">
      <li><a href="#">Aktualności</a></li>
      <li><a href="#">Nasz team</a></li>
      <li><a href="#">Historia</a></li>
  </ul>
</div>
Freestyle09
  • 4,894
  • 8
  • 52
  • 83

2 Answers2

1

I've modified the code to show the opacity of the pseudo element of the element the mouse is over.

const menuDropdown = document.querySelector('.menu-dropdown');
const about = document.querySelector('#about');

about.addEventListener('mouseover', function () {
  menuDropdown.classList.add('make-visible');
});
about.addEventListener('mouseout', function () {
 menuDropdown.classList.remove('make-visible');
});
.menu-dropdown:before {
    content: '';
    position: absolute;
    background-color: black;
    display: block;
    top: -15px;
    left: 50%;
    transform: translateX(-50%) rotate(45deg);
    height: 30px;
    width: 30px;
    opacity: 0;
    visibility: hidden;
}

.make-visible:before {
  opacity: 1;
  visibility: visible;
}
<div id="about">
  <ul class="menu-dropdown">
      <li><a href="#">Aktualności</a></li>
      <li><a href="#">Nasz team</a></li>
      <li><a href="#">Historia</a></li>
  </ul>
</div>
Thijs
  • 2,341
  • 2
  • 14
  • 22
  • Yeah I can show opacity value, but how to change it ?? I need to change opacity from 0 to 1 on before element, Can u edit this ? – Freestyle09 Sep 17 '18 at 12:56
  • Sorry, misunderstood your question. I don't think you can manipulate the style of a pseudo element through JS. You could however assign a class to the element which alters the opacity of the pseudo element. – Thijs Sep 17 '18 at 12:59
  • Ah ok... I understand now, Thanks for answer! – Freestyle09 Sep 17 '18 at 13:00
  • 1
    Updated the answer to show you how to add/remove the class. – Thijs Sep 17 '18 at 13:03
0

Try this getComputedStyle(document.querySelector('.menu-dropdown'), ':before')

Arek C.
  • 1,271
  • 2
  • 9
  • 17