Convert string to HTML in JavaScript - javascript

I have a string being sent to my JavaScript function from my C# code which has a text like:
Hi <b>Welcome to C#<sup>5.0</sup></b>
I'm populating a div with this string. I need this html content to be rendered in the screen with the bold and superscript applied as below
Hi Welcome to C#5.0
I tried the below it just displays the HTML tags as plain text
myfunction = function(data) {
var mytext = '<div>'+ data +'</div>;
$('#mydivid').after(mytext);
}
Is there any other solution neither like the one given here nor like this ?
Note: I cannot declare the string in a hidden variable in my .cshtml file within #HTML.Raw and again use it in my JavaScript.
I have tried using $.parseHTML but I got an error saying
$.parseHTML is not a function
Any solution other than the above solutions are welcome. Thanks in advance.

seems like nothing is wrong with your code. Check if some css is overriding the basic em and sup functionality.
for Example the default style of em is font-style: italic which chould be override by your css

Try like this
myfunction = function(data) {
$('#mydivid').html('<div>' + data + '</div>');
}

You listed JQuery in your tags so I figured this would help.
html = $.parseHTML( 'Hi <b>Welcome to C#<sup>5.0</sup></b>' );
Check out this JSFiddle
You can also do this if you want a javascript oneliner.
document.getElementById("mydivid").innerHTML="Hi <b>Welcome to C#<sup>5.0</sup></b>";

Related

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

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

Insert places Html in jQuery code

Hi i have a little problem.
I want use codes html to change style of texts,but i don't can import it into Jquery Scripts.
$('body').append($('<p>').html( <p id="text2">Data:<p>'Data:'+["Data"]));
How i have to do?
If you mean styling the object with css then here you go:
$('body').append($('<p>').css('cssproperty','value);
If you mean appending html to your object I would do:
var myNewHtmlP = $('<p id="text2">Data:<p>'Data:'+["Data"])');
myNewHtmlP.appendTo($('body'));
hey i think you search for this:
$('body').append( $('<p/>').attr('id', 'text2' ).html('myTestText'));
first you append the p tag, the slash is very important, after that the p tag get the id "text2" and after that you write the text 'myTestText' in the p tag

HTML DOM manipulation : properly replace tag by heading tag

I want to replace some tag-inside-a-paragraph-tag by a heading-tag-enclosed-by-a-paragraph tag. This would result in proper W3C coding, but it seems that jQuery is not able to manipulate the DOM in the right way!? I tried several ways of (jQuery) coding, but i can't get it to work ..
Original code:
<p>some text <span>replace me</span> some more text</p>
Desired code:
<p>some text</p><h2>my heading</h2><p>some more text</p>
Resulting code by jQuery replaceWith():
<p>some text<p></p><h2>my heading</h2><p></p>some more text</p>
Demo: http://jsfiddle.net/foleox/J43rN/4/
In this demo, look at "make H2 custom" : i expect this to work (it's a logical replace statement), but it results in adding two empty p-tags .. The other 2 functions ("make code" and "make H2 pure") are for reference.
Officially the W3C definition states that any heading tag should not be inside a paragraph tag - you can check this by doing a W3C validation. So, why does jQuery add empty paragraph tags? Does anybody know a way to achieve this? Am i mistaken somehow?
You can achieve this with this code. However it's pretty ugly:
$('.replaceMe').each(function() {
var $parent = $(this).parent(),
$h2 = $(this).before('$sep$').wrap('<h2>').parent().insertAfter($parent);
var split = $parent.html().split('$sep$');
$parent.before('<p>' + split[0] + '</p>');
$h2.after('<p>' + split[1] + '</p>');
$parent.remove();
});
http://jsfiddle.net/J43rN/5/
If you read the jQuery docs, you will find:
When the parameter has a single tag (with optional closing tag or
quick-closing) — $("<img />") or $("<img>"), $("<a></a>") or $("<a>")
— jQuery creates the element using the native JavaScript
createElement() function.
So that is exactly what it is doing. And as I said in my comment, you can't change a parent node from a child node, you're altering the DOM here, not HTML code. So you'll need to either use replaceWith on the parent node and replace everything or use something like remove and append to split it up in multiple elements which you append after each other.
Try this:
var temp = "<p>some text <span>replace me</span> some more text</p>";
temp.replace(/(\<span\>replace me\<\/span\>)/gi, '</p><h2>my heading</h2><p>');
This will do a case insensitive replace for multiple occurences as well.
Read more about capturing groups here
Original credit to this question!
Please try this I have updated the http://jsfiddle.net/J43rN/6/ example by the below java script function please check I hope it will work for you
function fnMakeCode() {
$('#myP #replaceMe').html("<code id='replaceMe'>My Code</code>");
}
function fnMakeH2pure() {
$('#myP #replaceMe').html("<h2 id='replaceMe'>My H2 pure</h2>");
}
function fnMakeH2custom() {
$('#replaceMe').html("<p></p>").html("<h2>My H2 custom</h2>");
}

Need Solution on NicEdit Insert HTML text into Instance

i am using this function to insert text into NicEdit,
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);}
This code works fine for simple text but when i pass HTML content into it, it does not render the HTML output in div instead it dumps the HTML code as it is into the Instance Div.
Example:
<div class="one">Some text here</div>
This must show in the Instance as "Some text here"
and remaining code hidden in source code.
Can any one give me a solution to fix this problem?
After working whole night and trying different solutions I had finally got it working! :)
In case any one wants to know solution for this, I had to add a Replace function
replace()
for the content and made it support HTML.
See my answer HERE. It's a plugin I created to insert html at the cursor position.

Categories