I have the following jQuery code:
$.each($(".coin"), function() {
var content = "/*:before content*/";
$("input", this).val(content);
});
I'd like to change the value of each input element using jQuery based on its pseudo element's content
property value (.coin:before
).
Here a example: http://jsfiddle.net/aledroner/s2mgd1mo/2/
According to MDN, the second parameter to the .getComputedStyle()
method is the pseudo element:
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt (Optional) - A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.
Therefore you could use the following in order to get the pseudo element's content
value:
window.getComputedStyle(this, ':before').content;
Updated Example
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$("input", this).val(content);
});
If you want to get the entity code based on the character, you can also use the following:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With