How to render HTML in string with Javascript? - javascript

I have the following javascript code:
var html = '<div class="col-lg-4 col-references" idreference="'+response+'"><span class="optionsRefer"><i class="glyphicon glyphicon-remove delRefer" style="color:red; cursor:pointer;" data-toggle="modal" data-target="#modalDel"></i><i class="glyphicon glyphicon-pencil editRefer" data-toggle="modal" data-target="#modalRefer" style="cursor:pointer;"></i></span><div id="contentRefer'+response+'">'+refer_summary+'</div><span id="nameRefer'+response+'">'+refer_name+'</span></div>';
$("#references").append(html);
When this code runs, the refer_summary variable actually contains a string which may contain HTML tags such as <b>, <i> etc., however, those tags are displayed on the page instead of rendering their behavior.
For example, on the page it would show <b> rather actually making the content bold.
How can I go about rendering the HTML tags when the value is appended?
In my Django template I use {% autoescape off %}{{content}}{% endautoescape %} so when I first load the page, the content is rendered correctly with bold etc. But how can I do the same thing when appending the html from javascript?
Thanks for the help!

You can render HTML using document.write()
document.write('<html><body><h2>HTML</h2></body></html>');
But to append existing HTML string, you need to get the id of the node/tag under which you want to insert your HTML string.
There are two ways by which you can possibly achieve this:
Using DOM -
var tag_id = document.getElementById('tagid');
var newNode = document.createElement('p');
newNode.appendChild(document.createTextNode('html string'));
Using innerHTML -
var tag_id = document.getElementById('tagid');
tag_id.innerHTML = 'HTML string';

Use $.parseHTML before the append html like as
var html = '<div class="col-lg-4 col-references" idreference="'+response+'"><span class="optionsRefer"><i class="glyphicon glyphicon-remove delRefer" style="color:red; cursor:pointer;" data-toggle="modal" data-target="#modalDel"></i><i class="glyphicon glyphicon-pencil editRefer" data-toggle="modal" data-target="#modalRefer" style="cursor:pointer;"></i></span><div id="contentRefer'+response+'">'+refer_summary+'</div><span id="nameRefer'+response+'">'+refer_name+'</span></div>';
html = $.parseHTML( html);
$("#references").append(html);

You can use Javascript's document.createRange().createContextualFragment:
const frag = document.createRange().createContextualFragment('<div>One</div><div>Two</div>');
console.log(frag);
/*
#document-fragment
<div>One</div>
<div>Two</div>
*/
https://davidwalsh.name/convert-html-stings-dom-nodes

If you want to do it in ReactJS, you can use "dangerouslySetInnerHTML" attribute, instead of "innerHTML" attribute.
As it allows the attackers to inject codes (XSS), it is named dangerous!
const myHtmlData = `
<ul>
<li>Item1<li>
<li>Item2<li>
</ul>`;
...
<div
dangerouslySetInnerHTML={{
__html: myHtmlData
}}>

You need to assign a particular div an id and then process/change UI in the specific div accordingly.
Given here is an excellent explanation.

Related

Why is my html entity not converting after wrapping it around a template literal?

What I am trying to do
I am trying to make my mailto ahref tag dynamically change the subject tag.
The Problem
I encoded my email to HTML entities (#) (I am using html entities to avoid spam-bots), so whenever I use template literal to wrap around the HTML entities, it doesn't convert anymore.
Example
This is the current working mailto ahref tag that does not have dynamic subject (this one works)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<h3>This is the current working mailto ahref tag that does not have dynamic subject</h3>
<a className="btn btn-primary mx-auto" href="mailto:henryly213#gmail.com?Subject=RandomSubject">
Contact Us
</a>
This is the mailto ahref tag that I attempting to do dynamic subjects
<h3>The Problem I am trying to solve</h3>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<a
className="btn btn-primary mx-auto"
href={`mailto:henryly213#gmail.com?Subject=${email}`}
>
Contact Us
</a>
What I have tried
I thought of putting the html entity in a variable and putting it inside the template literal; however it continue to not work.
//the code doesn't actually look like this but just a quick idea on what I did
const email = "mailto:henryly213#gmail.com"
const subject = "random subject"
<a className="btn btn-primary mx-auto" href={`${email}?Subject=${subject}`}>
Contact Us
</a>
The next thing I tried was concatenate a regular string with a template string but that also didn't work
const randomSubject = "hi";
const email ="mailto:sales#aeris.com.sg";
const subject = `?Subject=${randomSubject}`;
<a className="btn btn-primary mx-auto" href={email + subject}>
I would appreciate any help like changing of the code, links to post that solve this problem , or correction on my lack of knowledge.
React deals with the DOM not with raw HTML.
The JavaScript value you pass gets assigned as the value of the attribute in the DOM.
It is not passed through an HTML parser.
If you want to encode the characters in the string, do so with JavaScript escape sequences instead.

How can I render html code in a div using Javascript or jQuery

I'm trying to render some HTML on the fly in my website without success. I've tried using jQuery's .html() function as below:
My html
<div id='open_ender_output'></div>
My JQuery
var openEnderContent = "<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>"
//openEnderContent comes from my backend
$('#open_ender_output').html(openEnderContent)
The result is
<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>
Is there a way to make the browser render that result on the fly so it reflects the specific styles set on the text?
Decode the content by creating a temporary element.
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').html(
// create an element where the html content as the string
$('<div/>', {
html: openEnderContent
// get text content from element for decoded text
}).text()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>
Or you need to use a string which contains unescaped symbols.
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').append(openEnderContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>
You're on the right track. You need to differentiate between single and double quotes when creating a string. You're closing your string by adding double quotes inside double quotes.
Use the var below.
var openEnderContent = "<span style='color: #ff0000;'>DDD</span>!!!!!<strong>666666666666</strong></p>";
$('#open_ender_output').html(openEnderContent);
Fiddle for example: https://jsfiddle.net/acr2xg6u/
Change your jQuery to
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').append(openEnderContent);
Parsing problem from what I can tell.
"<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>"
You cannot create strings like that. If you are inside one, you must use the other:
"My name is 'Josh Crowe'"
'My name is "Josh Crowe"'
Here's corrected code:
"<p><span style='color: #ff0000;'>DDD</span>!!!!!<strong>666666666666</strong></p>"

How to decode string when using data-bind

I have meet with a problem.
In my view I use a span to bind my string.
<span data-bind="text: myString"></span>
In the model:
myString = '<b>I want Show in Bold!</b>';
It always show the origin string in my view.So how to make the view know it is a HTML tag?
Use html binding as per docs
<span data-bind="html: myString"></span>

How can I use a string in image `alt` tag without encode by AngularJs

If I have this AngularJs code:
<div class="myStyle">
TITLE:
{{product.title}}
</div>
I want show title without encode. so I know it's one solution:
<div class="myStyle">
TITLE:
<span ng-bind-html="product.title"></span>
</div>
But I don't happy about extra <span> code!
Also if I have this code:
<img src="img.jpg" alt="{{product.title}}">
I can not use extra span, Now how can I show title in alt tag of image without encode?!
I am assuming that since you use ng-bind-html that product.title is html string , not text
You could create a custom filter that returns text from html string
app.filter('htmlToText', function(){
return function(html){
return angular.element('<div>').append(html || '').text();
};
});
View
<img src="img.jpg" alt="{{product.title | htmlToText}}">
For showing product.title in div, if you don't like the extra span, you might try:
<div class="myStyle" ng-bind="product.title"></div>
where in your javascript code, you can add a prefix: "Title: " to product.title. (Although i don't feel having an extra span is bad)
Another side note, I see you are using ng-bind-html. Is "product.title" really html? If it contain some styles, maybe you can revise your "myStyle" to control the style. Let data be data.
For the image one, you probably don't need to worry about the {{ }}.
I am guessing the reason you don't like {{ }} is they may show briefly before angular can render the template with the data. However, if you put them in , the browser will not show content inside of alt unless your image is not available (If the image is really not available, you may consider revisiting your codes to make sure it is available, or to display a default image)

Get html content of a selector ( .html() ) with jQuery from a JavaScript variable that contains HTML

I have a javascript variable that contains a part of html code.
I need to get in this part of html code a div html content.
How can i do it ?
This is an example:
var code = '<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>';
I'd like get content of div "my_code" with Jquery .html();
How can i do it ?
Thanks
code variable it's just a string for your document. If you have parsed this HTML code inside the body then you can use $('#my_code'), otherwise it's still just a string so.. that's another story.
Check the other story here: http://jsfiddle.net/NSCQh/1/
I strongly suggest you have a look at jQuery's selector overview. They are the most important part of the jQuery magic, and without understanding them you'll get nowhere in the long run.
var html = $('#my_code').html()
or because that div containts text only
var txt = $('#my_code').text()
You've got a string, you need a DOM element. From that, you can get the jQuery object.
var el = document.createElement('div');
el.innerHTML = code;
console.log($(el));
pass the string to jquery and it works
var foo = '<div id="foo"> <span class="bar">fooBar</span> </div>';
var inside = $(foo).find('.bar').text();
alert(inside);
Create an ELEMENT, say p.
Use the following
$('<p>').append(code).find('div#my_code').html();
It create a p element, then append the content of variable code, then find div with id=my_code and select it's innerHTML.
Working model in the snippet.
var code = `<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>`;
var elm=$('<p>').append(code).find('div#my_code').html();
console.log(elm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories