0

I made this css code to style one of my input radio:

input[name=source]+span:after, input[name=source]:not(:checked)+span:before {
    border: 2px solid cyan;
}

now in my DOMContentLoaded i am attempting to modify the attributes of my input by doing this:

document.querySelector(`input[name=source]:not(:checked)+span:before`).style.border = 'border: 2px solid red';

But upon running I am getting this message:

Uncaught TypeError: Cannot read property 'style' of null
    at HTMLDocument.<anonymous>

If i only made this document.querySelector(`input[name=source] then nothing happens.

What should i do target those element? Why it is null?

  • Does this answer your question? [document.querySelector(...) is null error](https://stackoverflow.com/questions/20495960/document-queryselector-is-null-error) – norbitrial Apr 18 '20 at 18:49
  • You cannot target pseudo element, but there are [some workarounds...](https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin) – skobaljic Apr 18 '20 at 18:51

1 Answers1

0

The :before pseudo-element is created from css and you cannot access it from js with querySelector.

You could actually use getComputedStyle to access it but AFAIK this is read-only

const noCheckedLabel = document.querySelector('input[name=source]:not(:checked) + span');
window.getComputedStyle(noCheckedLabel, ':before')

Your best shot is to add this element a class that overrides the border color. However, I hardly see the utility of doing it in js when you can do it directly with a CSS selector.

Another thing that will never work is that you are trying to set a el.style.border = 'border: 2px solid red'. You should use instead el.style.border = '2px solid red'

Also, if you want to apply some styling to a pseudo-element you need to add a content: '' attribute

I would also suggest to add spaces to css selector and use ::before input[name=source]:not(:checked) + span::before

markusand
  • 235
  • 7
  • 18
  • I cannot change directly on my css because i am checking some of my input, if it has value then i will excute those changes on my radio button style and when i made this one ```document.querySelector(`input[name=source]:not(:checked)+span`).style.border = '2px solid #f44336';``` it create a border on the whole element that i.s the radio button plus its label. – Alexander Paudak Apr 18 '20 at 20:22
  • Still not sure about the final goal. Could you add a minimal reproductible example? Probably you’ll have to add more elements to your layout. – markusand Apr 18 '20 at 22:22