I have Googled my brains out and can't figure out how to make this work. Here is what I'm trying to do:
HTML:
<div id=derp>"Hi, my name is.."</div>
Javascript:
var div = document.getElementById('derp');
alert(div.innerHTML);
alert(div.innerText);
alert(div.textContent);
All of those alerts interpret and return the "
as "
in the resulting string. I want to get the raw text with "
uninterpreted.
They all return:
"Hi, my name is.."
When I want to get:
"Hi, my name is.."
Is there a way to do this? Preferably without trying to use a regex to replace every instance of "
with "
.
It's kind of a long story of what I'm trying to do, but simply using replace() to search and replace every instance of "
would be a headache to implement because of other regex matching/parsing that needs to occur.
Thanks in advance for any Javascript wizards who can save my sanity!
From the DOM, users can access HTML elements in five different ways in JavaScript. At below, users can see the demonstration of the above methods with the sample code.
The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection.
To quote bobince
When you ask the browser for an element node's innerHTML, it doesn't give you the original HTML source that was parsed to produce that node, because it no longer has that information. Instead, it generates new HTML from the data stored in the DOM. The browser decides on how to format that HTML serialisation; different browsers produce different HTML, and chances are it won't be the same way you formatted it originally.
In summary: innerHTML/innerText/text/textContent/nodeValue/indexOf
, none of them will give you the unparsed text.
The only possible way to do this is with regex, or you can do an ajax post to the page itself, but that is a bad practice.
I prepared some days ago a bin with some different approaches: http://jsbin.com/urazer/4/edit
My favorite:
var text = "<a href='#' title=\"Foo\"></a>");
var html = text.replace(/[<&>'"]/g, function(c) {
return "&#" + c.charCodeAt() + ";";
});
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