How to get the style of an element with psuedo-class (:focus for example)

150 Views Asked by At

I would like to get certain css property (for example the border-color) of any elements, but when its on a 'non-base' states, such as focus and hover. For example:

<style>
    .input {
        border: 1px solid red;
    }
    .input:focus {
        outline: none;
        border-color: green;
    }
</style>

<input type="text" class="input">

<script>
    let input = document.querySelector('.input');
    const inputBorderColor = window.getComputedStyle(input).getPropertyValue('border-color');
    console.log(inputBorderColor); // rgb(255, 0, 0)
</script>

Using getComputedStyle, I can grab the border color of the input for the 'base' state, but how do I get the border color for when the input is on focus (in this case border-color: green)?

2

There are 2 best solutions below

4
AudioBubble On
const input = document.querySelector('.input');
input.addEventListener("focus", function() {
  console.log(window.getComputedStyle(input).color)
});

Codepen: https://codepen.io/disaladamsas/pen/KKvNZYz?editors=1111

0
Mahdiar Mransouri On

the styles you write for hover and focus and other pseudo-classes are only applied to element when the element has the pseudo-class, a quick solution is to make the eventListener for the focus event like the previous answer and then triggering that event by JS on the load time

something like :

const input = document.querySelector('.input');
let color = '';
input.addEventListener("focus", function() {
    color = window.getComputedStyle(input).color;
});
input.dispatchEvent( new Event('focus') )