Assign CSS value within JS

Asked

Viewed 42 times

-1

I am trying to assign a CSS value via PURE JS.

This one worked :

$('a[title="Selecionar"]').css({ 'font-size':'0' });

But how do I do the :after css in this case ??? , like :

$('a[title="Selecionar"]').css({ ':after' : {'font-size':'14px','content':'adicionar'} })

the :after doesn’t want to work because I don’t know how to!

  • Hello Veronica, you already tried to do a quick search on the internet to know what you want, I did a search and the first link I entered I already found the answer, so questions like yours receive negative votes on the site (I was not the one who gave the negative), the answer to what you are looking for is here: https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin

  • Yes, I already searched. The one you searched for is CSS itself. I want to assign CSS inside a JS code

  • This does not work because JS does not have access to pseudo-elements. The JS manipulates the DOM and pseudo-elements are not part of the DOM (as its name says, "pseudo" is something that does not really exist). Another thing is that in the . css function you should put a pair of values (property, value), and :after is not CSS property. What you could do is add an element (a span) with .append().. the result would be the same with :after.

1 answer

0

This does not work because JS does not have access to pseudo-elements. The JS manipulates the DOM and pseudo-elements are not part of the DOM (as its name says, "pseudo" is something that does not really exist).

Another thing is that in function .css() you must put a pair of values (propriedade, valor), and :after is not CSS property.

What you could do is add an element (a span) with .append(). The result in practice would be the same as :after, with the advantage of being able to manipulate the span as you wish via JS.

See two examples, one with :after in CSS and other with .append() in the JS:

With :after

a[title="Selecionar"]:after{
   content: "olá";
   color: white;
   background-color: red;
}
<a href="" title="Selecionar">link</a>

With . append()

$("a[title='Selecionar']").append(
  '<span style="color: white; background-color: red;">olá</span>'
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="" title="Selecionar">link</a>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.