1
<span id="opensidebarid" class="icon"></span>

CSS:

.icon:before {
   content: 'close';
}

I want to change the content of :before using the ID from JavaScript (jQuery). How it is possible? I have tried with prop but not working at all.

aspile
  • 543
  • 8
  • 23
  • Somebody already answered this on this question -> https://stackoverflow.com/questions/317170/how-can-i-change-html-attribute-names-with-jquery – Pipo Jul 12 '20 at 07:09
  • Read more about jQuery `.css` here => [css](https://api.jquery.com/css/) – Always Helping Jul 12 '20 at 07:10
  • Does this answer your question? [How to change CSS using jQuery?](https://stackoverflow.com/questions/3730035/how-to-change-css-using-jquery) – Always Helping Jul 12 '20 at 07:11
  • May be you can't understand my question. This is not just changing CSS using jQuery. – aspile Jul 12 '20 at 08:40

2 Answers2

2

You can set an attribute in your css to get content data from there and then you can change that attribute using jQuery, since you cannot change the content of a :before element directly:

CSS:

.icon:before {
   content: attr(data);
}

jQuery:

$(document).ready(function(){
  $elem = $("#opensidebarid"); // Get element by ID.
  elemClass = $elem.attr("class"); // Get the class of that element in order to change content.
  $('.' + elemClass).attr('data', "open"); // Change attribute value of content.
});
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

After thinking a bit, I understood your question. ::before is a pseudo-selector, not a DOM element. So you can’t select it via jQuery.

You can toggleClass via jQuery if would like to change the ::before.

You could change it by creating a toggle class. For example:

.icon-toggle {content: "example" !important}

Then you can create either onclick or some action to toggle the change.

$("#opensidebarid").toggleClass("icon-toggle")

If you could write more detailed question I could help you more.

Pipo
  • 488
  • 2
  • 10