Get the value of a pseudo-element content property using JavaScript

I have the following jQuery code:

$.each($(".coin"), function() {
    var content = "/*:before content*/";
    $("input", this).val(content);
});

I would like to change the value of each input element using jQuery based on its property value contentfor the pseudo element content.

Here is an example: http://jsfiddle.net/aledroner/s2mgd1mo/2/

+4
source share
1 answer

According to MDN, the second parameter .getComputedStyle()is a pseudo-element:

var style = window.getComputedStyle(element[, pseudoElt]);

pseudoElt (optional) is a string indicating the correspondence of the pseudo-element. Must be omitted (or null) for regular elements.

content :

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

$('.coin').each(function() {
  var content = window.getComputedStyle(this, ':before').content;
  $("input", this).val(content);
});

, :

function getEntityFromCharacter(character) {
  var hexCode = character.replace(/['"]/g, '').charCodeAt(0).toString(16).toUpperCase();
  while (hexCode.length < 4) {
    hexCode = '0' + hexCode;
  }

  return '\\' + hexCode + ';';
}
$('.coin').each(function() {
  var content = window.getComputedStyle(this, ':before').content;
  $('input', this).val(getEntityFromCharacter(content));
});
.dollar:before {
  content: '\0024'
}
.yen:before {
  content: '\00A5'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="coin dollar">
  <input type="text" />
</div>
<div class="coin yen">
  <input type="text" />
</div>
Hide result
+2

Source: https://habr.com/ru/post/1618814/


All Articles