Converting string to HTML in JavaScript - javascript

I am extracting content from an HTML textarea using JS, in order to then put it into a <div>. Now, I know the content is going to be valid HTML - so I assumed that if I set it as the innerHTML of another element it would be parsed by the browser - but it's not. I'm getting the plain string (with tags and all) on the screen.
This is basically my script:
var txt = document.getElementById("contentTextArea").innerHTML; //Get the content
document.getElementById("contentOutput").innerHTML = txt;
Here's the HTML, just to be sure:
<textarea name="content" id="contentTextArea">
<p>Text...</p>
</textarea>
What am I doing wrong? Is there another way of doing this?
Thanks!

var txt = document.getElementById("contentTextArea").value; //Get the content

Textareas support value not innerHTML. YOu should do this...
document.getElementById("contentTextArea").value;

Related

Finding a div in a text variable with jQuery

I have a text variable in Javascript. Its name is text. It contains a whole HTML document. I've tried to find a jQuery selector that matches a contained div with id "mainContent":
var innerText = text.find('div[id=mainContent]');
Unfortunately, this does not work. The JavaScript somehow breaks at this point.
I've also tried it with:
var innerText = $(text).find('div[id=mainContent]');
But this also does break the JavaScript flow.
Does anybody have an idea?
If text is string then you should parse them first, you can do so using jQuery.parseHTML().
Demo:
var text = `<div><div id="mainContent">Test Container</div></div>`;
text = $.parseHTML(text);
console.log($(text).find('div#mainContent'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How do you insert HTML into a QuillJS?

Is it possible to insert raw HTML into a Quill? I've been searching the documentation but couldn't find anything.
If it's not possible, can I at least convert HTML into a Quill Delta?
The reason I need this is because I am grabbing the raw HTML of the text taken from Quill, so I can view it later in HTML style. Have I been doing everything wrong, and need to keep a Delta version of it as well?
On version 1.3.6,
You can use Quill.setContents(value) method.
And insert your new HTML like this:
const value = `<h1>New content here</h1>`
const delta = quill.clipboard.convert(value)
quill.setContents(delta, 'silent')
Quill documentation: https://quilljs.com/docs/api/#setcontents
I have found a way, looking extremely closely at the documentation. Method quill.clipboard.dangerouslyPasteHTML('raw html'); does the trick. https://quilljs.com/docs/modules/clipboard/#dangerouslypastehtml
Another way to insert HTML into Quill is by using vanilla JavaScript.
You can set your html to a variable, such as htmlToInsert.
Then target the contenteditable div created by Quill, by getting it by its class, ql-editor.
Finally, set the innerHTML of that div to the HTML you want to insert.
For example:
var htmlToInsert = "<p>here is some <strong>awesome</strong> text</p>"
var editor = document.getElementsByClassName('ql-editor')
editor[0].innerHTML = htmlToInsert
There is better way to do this:
const htmlMurkup = '<p>Good</p>'
let quill = new Quill()
quill.container.firstChild.innerHTML = htmlMurkup
I believe the most straight forward way is this:
quill.root.innerHTML = '<p>HTML Goes Here</p>'
You can also obtain the HTML from this property as well.
If you aren't getting the desired output. It could be because your html content is encoded.
Use this to convert it.
let realHTML = $('<textarea />').html("<p><strong>Hello</strong></p><p><br></p>").text();
console.log(realHTML);
This code will output
<p><strong>Hello</strong></p>
After this you can use this command to set the html content in quill editor
quill.root.innerHTML = realHTML;
or even this:
let initialContent = quill.clipboard.convert(realHTML);
quill.setContents(initialContent, 'silent');
Its proper your html is in the real html format before setting the value on quill. Else the html tags would be displayed verbally.
Just to add to #user1993629's answer, using quill.clipboard.dangerouslyPasteHtml(0, "raw html") will place the cursor at the end of the pasted content

String Filtering.Need to remove the <style> tag and its contents and keep only the contents in <body>

In our project, we are getting a response from the DB. We are using the same string in two ways.
We have to display the text part alone in one line
We are putting the entire content as an HTML.
We are getting a response similar to this.
"<html><head><title>SomeTitle</title></head><style>a.hover{color:green}cc.a{color:red},pq.a{text-decoration:underline}</style> <body> Some content </body></html>"
I need to get the content only from the body using string manipulation.I need to filter out all the contents of the other tags as well.
For example
Final result should be
Some content
I used text() in some case but at times the content inside is also getting displayed. That is not allowed for me.
Note: There are times where I don't get so there should be a check for that as well.
any solution on this?
At times we are getting inside body as well. So is there any way to remove that part off?
for example
var str = "<html><head><title>SomeTitle</title></head><style>a.hover{color:green}cc.a{color:red},pq.a{text-decoration:underline}</style> <body> <style>.hello12{color:green}</style>Some content </body></html>";
and i should get just "some content"
Use DOMParser and get text content from body tag. Where querySelector can be used to get body element and get text content from textContent property.
var str = "<html><head><title>SomeTitle</title></head><style>a.hover{color:green}cc.a{color:red},pq.a{text-decoration:underline}</style> <body> Some content </body></html>";
var parser = new DOMParser();
var doc = parser.parseFromString(str, "text/html");
console.log(
doc.querySelector('body').textContent
)
FYI : To avoid script and style tag content use innerText property instead of textContent property.

How to copy HTML tags to clipboard without changes?

I am using this SO answer to copy page content using pure JavaScript on user click. However my content contains HTML tags:
<script>http://localhost:3000/widget/174b6b69bcf352803a00</script>
When pasted from the clipboard it turns into this:
<script>http://localhost:3000/widget/174b6b69bcf352803a00</script>
How can I revert it back?
Use innerText instead of innerHTML to get the plain text version without HTML tags in it.
Here is a way to parse HTML entities :
function parseHTMLEntities(htmlString) {
var e = document.createElement("div");
e.innerHTML = htmlString;
return e.innerText;
}
// use like this :
var text = parseHTMLEntities("<script>http://localhost:3000/widget/174b6b69bcf352803a00</script>");
alert(text);
I mistook URI ecoding with HTML entities...
That was a stupid mistake...
see this question:
How to convert characters to HTML entities using plain JavaScript

jQuery: Best way to append to html of a paragraph inside a textarea

I have a textarea that contains variable html content which is always wrapped in a paragraph (p) tag.
HTML (before appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content.</p></textarea>
I fetch this content using the following in jQuery:
jQuery:
$('#comments').val();
Now I need to append HTML at the end of this paragraph but inside the p tag.
HTML (after appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content. Some appended HTML.</p></textarea>
I can of course replace the last 4 characters of the above (which is the closing p tag), then append my HTML and then add the closing p tag again.
Can someone tell me if there is a better way to achieve the same in jQuery ?
Many thanks in advance for this, Tim.
Parse the string value of the textarea as HTML, and insert whatever you like, then pass the string value of the HTML back
$('#comments').val(function(_, val) {
return $('<div />', {html:val}).find('p').append('content').end().html();
});
FIDDLE
This could do the trick
var html = $('#comments').val();
$('#comments').val(
$(html).append(' Some appended HTML.')[0].outerHTML
);
DEMO
You could insert the value into a temporary div, add an element to the <p>-element inside the temporary div and fetch the renewed content again:
var tmpDiv = $('<div></div>'); //create temporary element
tmpDiv.html($('#comments').val()); // add HTML from textarea
$(someHtml).appendTo($('p', tmpDiv)); // append custom HTML to P inside temp element
newTextAreaValue = tmpDiv.html(); // retrieve new value
Ok. I REALLY love this!
$('#comments').text($($('#comments').text()).append(' a new insert!').text());
Don't look at it too long. Could hurt your eyes :-)

Categories