1

I would like to get the content from my :before tag. I know some will say it's not a real (pseudo) element but there is a way in JS but can some one help me do it in JQ because I have multiple tags and I want to iterate with $.each...

Here is how I got the content in JS

window.getComputedStyle(document.querySelector('i'), ':before').getPropertyValue('content')

How can I do this in JQ?

Here is what I tried:

$.each($('div'),function(){
 $(this).find('i:before').css('content');
});

Print a special char?

When I get the content I would like to print it, the problem is it's a special character and I would like to get a real code.

My content has a code like this: \e002. So I would like to print it like that not .

Cœur
  • 37,241
  • 25
  • 195
  • 267
Maverick
  • 876
  • 2
  • 12
  • 22

1 Answers1

2

Iterate $.each($('div i') instead of $.each($('div'), so you can avoid using find() within the iterator.

You can then use your window.getComputedStyle() code on this:

window.getComputedStyle(this, ':before').getPropertyValue('content')

You'll then be left with a Unicode string, which brings us to the second part of your question.

You can use charCodeAt() to view this string character by character, which gives the following for \e002:

  • 34
  • 57346
  • 34

The 34s represent double-quotes, which you can ignore.

57346 is the decimal equivalent of hexadecimal e002. You can use toString(16) to convert it to hex.

All that's left is to prepend the \ in front.

So our code becomes:

$.each($('div i'),function() {
  var s = window.getComputedStyle(this, ':before').getPropertyValue('content'),
      char = '\\' + s.charCodeAt(1).toString(16);

  console.log(char);  // \e002
});

Snippet:

$.each($('div i'),function() {
  var s = window.getComputedStyle(this, ':before').getPropertyValue('content'),
      char = '\\' + s.charCodeAt(1).toString(16);
  
  console.log(char);  // \e002
});
i:before {
  content: '\e002';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <i>Our italic node</i>
</div>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79