1

I'm grabbing the text value from a div, setting it as a variable, and then I need to add parenthesis and a backslash to it. The end result should be: "\f333". Once I have "\f333", I need to add this to a pseudo element.

HTML

<div class="icon">f333</div>

jQuery

var iconOne = """ + "\" $('.icon').text() + "";
$('.nav:before').css('content', iconOne);

CSS (What I want the end the result to be:

.nav:before {
  content: "\f333";
 }

Unfortunately, the CSS isn't being applied to the pseudo element and I think it has to do with the jQuery. Any help in applying the parenthesis and backslash correctly, please?

Weebs
  • 155
  • 2
  • 10

1 Answers1

0

It's possible to set data attribute of .nav via jQuery (for example data-symbol) and then refer to this attribute from CSS:

nav:before {
  content: attr(data-symbol);
}

You cannot access pseudo elements with Javascript because they are not in the DOM.

You can, however, create a style element dynamically, define a new css class in that and add that class to the element:

let div = document.getElementById('div');
let icon = document.getElementById('icon').textContent;
let button = document.getElementById('button');

button.addEventListener('click', (e) => {
  const style = document.createElement('style');
  style.textContent = `.icon-victory::before { content: "${icon} "; }`;
  document.body.appendChild(style);
  div.textContent = div.textContent.replace("wants", "has");
  div.classList.add('icon-victory');
  document.body.removeChild(button);
})
#icon {
  display: none;
}
<body>
  <div id="icon">✌</div>
  <div id="div">This Div wants an icon!</div>
  <button id="button" type="button">Click to add icon to div#div</button>
</body>
connexo
  • 53,704
  • 14
  • 91
  • 128