Home > Enterprise >  Javascript if svg has role add class
Javascript if svg has role add class

Time:07-31

I'm trying to add a class to an SVG if the does not have a role="img".

I can add a class to the SVG with role img

const imgRole = document.querySelectorAll('svg[role="img"]');

imgRole.forEach(function(el) {
  el.classList.add("my--class");
});

However I can't target the SVGs that do not have the role.

I tried to find a way of using not !, but had no success.

if (!el.classList.contains...

I'd appreciate any help in showing me how to achieve this.

CodePudding user response:

Try using :not

document.querySelectorAll('p:not([role=a])').forEach(p => p.style.color = 'red')
<p role="a">lorem ipsum</p>
<p role="not a">lorem ipsum</p>
<p role="a">lorem ipsum</p>
<p role="also not a">lorem ipsum</p>

In your case:

'svg:not([role="img"])'
  • Related