Reputation: 1793
I want to get the content of an element without it being parsed. In this case the results should be é however all methods I tried parse the content and return é. How do I get the actual content.
console.log('javascript textContent:'+document.getElementById('test').textContent);
console.log('javascript innerText:'+document.getElementById('test').innerText);
console.log('javascript innerHTML:'+document.getElementById('test').innerHTML);
console.log('jQuery text():'+$('#test').text());
console.log('jQuery html():'+$('#test').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">é</div>
Upvotes: 5
Views: 349
Reputation: 1737
The most simple approach would be to use a "backend" language to transform your given char since most of them (for example PHP and .net) provide a built-in function for that.
Unfortunately there is no existing vanilla function that implements this in javascript (at least not to my knowledge).
For example in php this would be:
string htmlentities(string $string....)
For javascript you could create your own solution. Basically create a list of your needed html entities or take a pre-defined list like this (https://raw.githubusercontent.com/w3c/html/master/entities.json) and work from there on.
Iterate over each object and check if your searched character (é) is present in an object.
To speed up the process I'd save the JSON file to your webhost and maybe reduce its size by removing not needed entities.
It may not be the most beautiful solution but definetly does the job pretty well.
let element = document.getElementById('test').textContent;
fetch("https://raw.githubusercontent.com/w3c/html/master/entities.json")
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
Object.keys(data).forEach(function(key){
if (data.hasOwnProperty(key)){
if(data[key].characters === element) {
console.log(key);
}
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">é</div>
Upvotes: 2