Transform plain text as a css value with javascript - javascript

I'm making a style guide and I have disabled css in pre markup that I'm trying to apply as valid css to example boxes above.
Easier to understand with markup (please don't mind the weird indentation, it's done on purpose to simplify rendering. Also "defaut" is the french word for "default") :
<div id="styleguide" class="field-style">
<div class="colored">
</div>
<pre><code class="language-less">
#defaut: #000;
</code></pre>
<div class="colored">
</div>
<pre><code class="language-less">
#defaut: #e55240;
</code></pre>
<div class="colored">
</div>
<pre><code class="language-less">
#defaut: #fff;
</code></pre>
</div>
I tried several variations but it doesn't work. Here is my latest attempt. In here I'm trying to select via regex everything up to and including '#', and delete it. Then I get the numbers and put them in background style. You could say I should filter directly to only select numerical values via regex, but it didnt't work either and I don't know why
$('.field-style .colored').each(function() {
var $this = $(this);
$this.css(
'background', '#' +
$this
.next('pre')
.children('code')
.text()
.replace('/^(.*?\\#)|;/', '')
);

You could try to use the colon to split the text and take the second value resulting from it, then removing the semicolon:
$(this).css(
'background',
$(this).next().text()
.split(':')[1]
.trim()
.replace(';','')
);

Apart from ensuring that your target divs are either not empty or have some height, you need to:
either replace your prefix and trim the textContent to get rid of trailing spaces/breaks along with getting rid of the last ;:
$this.next().find('code').text().replace('#defaut: ', '').trim().slice(0, -1)
or split on : and rest on the second element of the resulting array:
$this.next().find('code').text().split(':')[1].trim().slice(0, -1)
Demo:
$('.colored').each(function() {
var $this = $(this),
prop = $this.next().find('code').text().replace('#defaut: ', '').trim().slice(0, -1)
;
$this.css({'background-color': prop });
});
div.colored { height: 16px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="styleguide" class="field-style">
<div class="colored">First</div>
<pre><code class="language-less">
#defaut: #f00;
</code></pre>
<div class="colored">Second</div>
<pre><code class="language-less">
#defaut: #0f0;
</code></pre>
<div class="colored">Third</div>
<pre><code class="language-less">
#defaut: #00f;
</code></pre>
</div>

There's a two issues with your regular expression:
There's a newline between the code tag and #defaut which will not be matched by the .. From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions:
(The decimal point) matches any single character except the newline character.
Use trim() to get rid of leading and trailing space.
The regular expression must not be enclosed in quotes, otherwise it will be treated as a regular string. Use replace(/^(.*?\\#)|;/) instead.
As a further note it might be better to get the color value by extracting it instead of deleting everything else around it:
$this
.next('pre')
.children('code')
.text().match(/#defaut:\s*(#.+?);/)[1]
This regular expression will look for "#defaut:" potentially followed whitespace, then followed by a color value terminated by a semicolon and extract the color value. An added avantage is that this solution won't break as easily in case you have to add more data inside the <code> tag or change the formatting.

Related

Regular Expression

I've needed to display an alert in case there's a text input includes a double-quote which isn't followed by a backslash. So I used 'negative lookbehind' regular expression and achieved that goal.
text.innerHTML.match(/(?<!\\)\"/);
" -> Alert
\" -> OK
However, I found an issue that when users put an indent into text box, the WYSIWYG (Quill) generates a class named "ql-indent-N (indent level starting from 1)" which triggers an alert by " detection.
Thus, I added another exception to the original regular expression like below.
text.innerHTML.match(/(?<!\\)(?<!class=)\"/);
But it didn't work so I tried some tests in console, and saw that
it works fine when I just put
class=" -> OK
while, it does not work when it's inside real tag like
<p class="ql-indent-1"> text </p> -> Alert
How can I make a lookbehind reg exp working fine with those <p class=" ...">? Or any other generous suggestion to achieve the same goal — Displaying an alert to double-quotes not followed by a backslash nor by <p class=" ...">? Below is a basic structure of the textbox.
<div class="ql-editor" data-gramm="false" contenteditable="true">
<p>text</p>
</div>
Dealing Quill's delta format is very complicated.
As mentioned in the comment, you could refer to the element innerText rather than its innerHTML in order to ignore any tag inserted by the WYSIWYG editor.
Example (here I am using RegExp.prototype.test() rather than RegExp.prototype.match())
const qEditor = document.querySelector('.ql-editor');
const re = /(?<!\\)"/gm;
qEditor.addEventListener('input', () => {
if (re.test(qEditor.innerText)){
window.alert('All double-quotes (") must be escaped (\\")');
}
})
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<div id="editor" class="ql-editor" data-gramm="false" contenteditable="true">
<p>text</p>
</div>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
var quill = new Quill('#editor', {
theme: 'snow'
});
</script>

How can I render raw HTML [duplicate]

How can I show HTML snippets on a webpage without needing to replace each < with < and > with >?
In other words, is there a tag for don't render HTML until you hit the closing tag?
The tried and true method for HTML:
Replace the & character with &
Replace the < character with <
Replace the > character with >
Optionally surround your HTML sample with <pre> and/or <code> tags.
sample 1:
<pre>
This text has
been formatted using
the HTML pre tag. The brower should
display all white space
as it was entered.
</pre>
sample 2:
<pre>
<code>
My pre-formatted code
here.
</code>
</pre>
sample 3:
(If you are actually "quoting" a block of code, then the markup would be)
<blockquote>
<pre>
<code>
My pre-formatted "quoted" code here.
</code>
</pre>
</blockquote>
is there a tag for don't render HTML until you hit the closing tag?
No, there is not. In HTML proper, there’s no way short of escaping some characters:
& as &
< as <
(Incidentally, there is no need to escape > but people often do it for reasons of symmetry.)
And of course you should surround the resulting, escaped HTML code within <pre><code>…</code></pre> to (a) preserve whitespace and line breaks, and (b) mark it up as a code element.
All other solutions, such as wrapping your code into a <textarea> or the (deprecated) <xmp> element, will break.1
XHTML that is declared to the browser as XML (via the HTTP Content-Type header! — merely setting a DOCTYPE is not enough) could alternatively use a CDATA section:
<![CDATA[Your <code> here]]>
But this only works in XML, not in HTML, and even this isn’t a foolproof solution, since the code mustn’t contain the closing delimiter ]]>. So even in XML the simplest, most robust solution is via escaping.
1 Case in point:
textarea {border: none; width: 100%;}
<textarea readonly="readonly">
<p>Computer <textarea>says</textarea> <span>no.</span>
</textarea>
<xmp>
Computer <xmp>says</xmp> <span>no.</span>
</xmp>
Kind of a naive method to display code will be including it in a textarea and add disabled attribute so its not editable.
<textarea disabled> code </textarea>
Hope that help someone looking for an easy way to get stuff done.
But warning, this won't escape the tags for you, as you can see here (the following obviously does not work):
<textarea disabled>
This is the code to create a textarea:
<textarea></textarea>
</textarea>
Deprecated, but works in FF3 and IE8.
<xmp>
<b>bold</b><ul><li>list item</li></ul>
</xmp>
Recommended:
<pre><code>
code here, escape it yourself.
</code></pre>
i used <xmp> just like this :
http://jsfiddle.net/barnameha/hF985/1/
The deprecated <xmp> tag essentially does that but is no longer part of the XHTML spec. It should still work though in all current browsers.
Here's another idea, a hack/parlor trick, you could put the code in a textarea like so:
<textarea disabled="true" style="border: none;background-color:white;">
<p>test</p>
</textarea>
Putting angle brackets and code like this inside a text area is invalid HTML and will cause undefined behavior in different browsers. In Internet Explorer the HTML is interpreted, whereas Mozilla, Chrome and Safari leave it uninterpreted.
If you want it to be non-editable and look different then you could easily style it using CSS. The only issue would be that browsers will add that little drag handle in the bottom-right corner to resize the box. Or alternatively, try using an input tag instead.
The right way to inject code into your textarea is to use server side language like this PHP for example:
<textarea disabled="true" style="border: none;background-color:white;">
<?php echo '<p>test</p>'; ?>
</textarea>
Then it bypasses the html interpreter and puts uninterpreted text into the textarea consistently across all browsers.
Other than that, the only way is really to escape the code yourself if static HTML or using server-side methods such as .NET's HtmlEncode() if using such technology.
If your goal is to show a chunk of code that you're executing elsewhere on the same page, you can use textContent (it's pure-js and well supported: http://caniuse.com/#feat=textcontent)
<div id="myCode">
<p>
hello world
</p>
</div>
<div id="loadHere"></div>
document.getElementById("myCode").textContent = document.getElementById("loadHere").innerHTML;
To get multi-line formatting in the result, you need to set css style "white-space: pre;" on the target div, and write the lines individually using "\r\n" at the end of each.
Here's a demo: https://jsfiddle.net/wphps3od/
This method has an advantage over using textarea: Code wont be reformatted as it would in a textarea. (Things like are removed entirely in a textarea)
In HTML? No.
In XML/XHTML? You could use a CDATA block.
I assume:
you want to write 100% valid HTML5
you want to place the code snippet (almost) literal in the HTML
especially < should not need escaping
All your options are in this tree:
with HTML syntax
there are five kinds of elements
those called "normal elements" (like <p>)
can't have a literal <
it would be considered the start of the next tag or comment
void elements
they have no content
you could put your HTML in a data attribute (but this is true for all elements)
that would need JavaScript to move the data elsewhere
in double-quoted attributes, " and &thing; need escaping: " and &thing; respectively
raw text elements
<script> and <style> only
they are never rendered visible
but embedding your text in Javascript might be feasable
Javascript allows for multi-line strings with backticks
it could then be inserted dynamically
a literal </script is not allowed anywhere in <script>
escapable raw text elements
<textarea> and <title> only
<textarea> is a good candidate to wrap code in
it is totally legal to write </html> in there
not legal is the substring </textarea for obvious reasons
escape this special case with </textarea or similar
&thing; needs escaping: &thing;
foreign elements
elements from MathML and SVG namespaces
at least SVG allows embedding of HTML again...
and CDATA is allowed there, so it seems to have potential
with XML syntax
covered by Konrad's answer
Note: > never needs escaping. Not even in normal elements.
It's vey simple ....
Use this xmp code
<xmp id="container">
<xmp >
<p>a paragraph</p>
</xmp >
</xmp>
<textarea ><?php echo htmlentities($page_html); ?></textarea>
works fine for me..
"keeping in mind Alexander's suggestion, here is why I think this is a good approach"
if we just try plain <textarea> it may not always work since there may be closing textarea tags which may wrongly close the parent tag and display rest of the HTML source on the parent document, which would look awkward.
using htmlentities converts all applicable characters such as < > to HTML entities which eliminates any possibility of leaks.
There maybe benefits or shortcomings to this approach or a better way of achieving the same results, if so please comment as I would love to learn from them :)
This is a simple trick and I have tried it in Safari and Firefox
<code>
<span><</span>meta property="og:title" content="A very fine cuisine" /><br>
<span><</span>meta property="og:image" content="http://www.example.com/image.png" />
</code>
It will show like this:
You can see it live Here
You could try:
Hello! Here is some code:
<xmp>
<div id="hello">
</div>
</xmp>
This is a bit of a hack, but we can use something like:
body script {
display: block;
font-family: monospace;
white-space: pre;
}
<script type="text/html">
<h1>Hello World</h1>
<ul>
<li>Enjoy this dodgy hack,
<li>or don't!
</ul>
</script>
With that CSS, the browser will display scripts inside the body. It won’t attempt to execute this script, as it has an unknown type text/html. It’s not necessary to escape special characters inside a <script>, unless you want to include a closing </script> tag.
I’m using something like this to display executable JavaScript in the body of the page, for a sort of "literate progamming".
There’s some more info in this question When should tags be visible and why can they?.
function escapeHTML(string)
{
var pre = document.createElement('pre');
var text = document.createTextNode(string);
pre.appendChild(text);
return pre.innerHTML;
}//end escapeHTML
it will return the escaped Html
Ultimately the best (though annoying) answer is "escape the text".
There are however a lot of text editors -- or even stand-alone mini utilities -- that can do this automatically. So you never should have to escape it manually if you don't want to (Unless it's a mix of escaped and un-escaped code...)
Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html
This is by far the best method for most situations:
<pre><code>
code here, escape it yourself.
</code></pre>
I would have up voted the first person who suggested it but I don't have reputation. I felt compelled to say something though for the sake of people trying to find answers on the Internet.
You could use a server side language like PHP to insert raw text:
<?php
$str = <<<EOD
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Minimal HTML5">
<meta name="keywords" content="HTML5,Minimal">
<title>This is the title</title>
<link rel='stylesheet.css' href='style.css'>
</head>
<body>
</body>
</html>
EOD;
?>
then dump out the value of $str htmlencoded:
<div style="white-space: pre">
<?php echo htmlentities($str); ?>
</div>
There are a few ways to escape everything in HTML, none of them nice.
Or you could put in an iframe that loads a plain old text file.
Actually there is a way to do this. It has limitation (one), but is 100% standard, not deprecated (like xmp), and works.
And it's trivial. Here it is:
<div id="mydoc-src" style="display: none;">
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
<!--
YOUR CODE HERE.
<script src="WidgetsLib/all.js"></script>
^^ This is a text, no side effects trying to load it.
-->
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
</div>
Please let me explain. First of all, ordinary HTML comment does the job, to prevent whole block be interpreted. You can easily add in it any tags, all of them will be ignored. Ignored from interpretation, but still available via innerHTML! So what is left, is to get the contents, and filter the preceding and trailing comment tokens.
Except (remember - the limitation) you can't put there HTML comments inside, since (at least in my Chrome) nesting of them is not supported, and very first '-->' will end the show.
Well, it is a nasty little limitation, but in certain cases it's not a problem at all, if your text is free of HTML comments. And, it's easier to escape one construct, then a whole bunch of them.
Now, what is that weird LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo string? It's a random string, like a hash, unlikely to be used in the block, and used for? Here's the context, why I have used it. In my case, I took the contents of one DIV, then processed it with Showdown markdown, and then the output assigned into another div. The idea was, to write markdown inline in the HTML file, and just open in a browser and it would transform on the load on-the-fly. So, in my case, <!-- became transformed to <p><!--</p>, the comment properly escaped. It worked, but polluted the screen. So, to easily remove it with regex, the random string was used. Here's the code:
var converter = new showdown.Converter();
converter.setOption('simplifiedAutoLink', true);
converter.setOption('tables', true);
converter.setOption('tasklists', true);
var src = document.getElementById("mydoc-src");
var res = document.getElementById("mydoc-res");
res.innerHTML = converter.makeHtml(src.innerHTML)
.replace(/<p>.{0,10}LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo.{0,10}<\/p>/g, "");
src.innerHTML = '';
And it works.
If somebody is interested, this article is written using this technique. Feel free to download, and look inside the HTML file.
It depends what you are using it for. Is it user input? Then use <textarea>, and escape everything. In my case, and probably it's your case too, I simply used comments, and it does the job.
If you don't use markdown, and just want to get it as is from a tag, then it's even simpler:
<div id="mydoc-src" style="display: none;">
<!--
YOUR CODE HERE.
<script src="WidgetsLib/all.js"></script>
^^ This is a text, no side effects trying to load it.
-->
</div>
and JavaScript code to get it:
var src = document.getElementById("mydoc-src");
var YOUR_CODE = src.innerHTML.replace(/(<!--|-->)/g, "");
This is how I did it:
$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";
It may not work in every situation, but placing code snippets inside of a textarea will display them as code.
You can style the textarea with CSS if you don't want it to look like an actual textarea.
If you are looking for a solution that works with frameworks.
const code = `
<div>
this will work in react
<div>
`
<pre>
<code>{code}</code>
</pre>
And you can give it a nice look with css:
pre code {
background-color: #eee;
border: 1px solid #999;
display: block;
padding: 20px;
}
JavaScript string literals can be used to write the HTML across multiple lines. Obviously, JavaScript, ECMA6 in particular, is required for this solution.
.createTextNode paired with CSS white-space: pre-wrap; does the trick.
.innerText alone also works. Run code snippet below.
let codeBlock = `
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome to my page</h1>
<p>I like cars and lorries and have a big Jeep!</p>
<h2>Where I live</h2>
<p>I live in a small hut on a mountain!</p>
</body>
</html>
`
const codeElement = document.querySelector("#a");
let textNode = document.createTextNode(codeBlock);
codeElement.appendChild(textNode);
const divElement = document.querySelector("#b");
divElement.innerText = codeBlock;
#a {
white-space: pre-wrap;
}
<div id=a>
</div>
<div id=b>
</div>
//To show xml tags in table columns you will have to encode the tags first
function htmlEncode(value) {
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
html = htmlEncode(html)
A combination of a couple answers that work together here:
function c(s) {
return s.split("<").join("<").split(">").join(">").split("&").join("&")
}
displayMe.innerHTML = ok.innerHTML;
console.log(
c(ok.innerHTML)
)
<textarea style="display:none" id="ok">
<script>
console.log("hello", 5&9);
</script>
</textarea>
<div id="displayMe">
</div>
I used this a long time ago and it did the trick for me, I hope it helps you too.
var preTag = document.querySelectorAll('pre');
console.log(preTag.innerHTML);
for (var i = 0; i < preTag.length; i++) {
var pattern = preTag[i].innerHTML;
pattern = pattern.replace(/</g, "<").replace(/>/g, ">");
console.log(pattern);
preTag[i].innerHTML = pattern;
}
<pre>
<p>example</p>
<span>more text</span>
</pre>
You can separate the tags by changing them to spans.
Like this:
<span><</span> <!-- opening bracket of h1 here -->
<span>h1></span> <!-- opening tag of h1 completed here -->
<span>hello</span> <!-- text to print -->
<span><</span> <!-- closing h1 tag's bracket here -->
<span>/h1></span> <!-- closing h1 tag ends here -->
And also, you can just only add the <(opening angle bracket) to the spans
<span><</span> <!-- opening bracket of h1 here -->
h1> <!-- opening tag of h1 completed here -->
hello <!-- text to print -->
<span><</span> <!-- closing h1 tag's bracket here -->
/h1><!-- closing h1 tag ends here -->
<code><?php $str='<';echo htmlentities($str);?></code>
I found this to be the easiest, fastest and most compact.

JQuery - Paste event, stripping rich text

I have a contentEditable field where I'd like to do the following. When a user pastse rich text into the field (microsoft word, or otherwise) I'd like to strip all the rich text, but retain the line breaks.
My thinking was: If you paste rich text into a plain <texarea>, it removes all the formatting and retains the breaks (created by explicit new lines, as well as block level elements). I'd like to somehow simulate this. In other words, create a temporary textarea, intercept the paste event, apply it to the Textarea, retrieve the results, and insert them back into the original Content Editable field.
However, i haven't found a way to simulate this. If I paste the contents into a textarea via jquery, it seems to retan all the rich text formatting when I try and copy it from there, back to the original fields
You could achieve something like this without needing a textarea, just processing the code in the content editable div every time that there is a change in its value, and removing all the tags but the paragraphs and line breaks.
The idea would be that every time that the content changes in the div (listen to the input event):
Replace in the inner HTML all </p> and <br> for non-HTML tokens (e.g.: [p] and [br] respectively).
Remove all HTML tags (you can do it with .text())
Replace the tokens that you used for their equivalents (and their openings!)
Wrap everything between <p> and </p>.
Here a simple demo:
$("#editable").on("input", function() {
$this = $(this);
// replace all br and closing p tags with special tokens
$this.html($this.html().replace(/\<\/p\>/g,"[p]").replace(/\<br\>/g,"[br]"));
// remove all the tags, and then replace the tokens for their original values
$this.html("<p>" + $this.text().replace(/\[p\]/g, "</p><p>").replace(/\[br\]/g,"<br>") + "</p>");
});
div#editable, div#demo {
border:1px solid gray;
padding:6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div contenteditable="true" id="editable"></div>
<h3>Demo</h3>
<p>Copy this code and paste it on the editable div above:</p>
<div id="demo">
<p>This <b>is</b> <i>a</i> styled paragraph.</p>
<p> </p>
<p>The <span style="font-weight:bold">above paragraph</span> is empty.</p>
<p>And this is a new paragraph…<br>with a line break!</p>
</div>
You can also see it running on this JSFiddle: http://jsfiddle.net/v5rae96w/
I tried this solution with MS Word and HTML and it works fine. But it has one issue: it only does line breaks with p and br (that works nicely with MS Word and other word processors). If the user copies HTML like div (or other block elements that cause a line break), it won't work as nicely. If you need to break with all block elements, this solution may require some changes.
To fix that, you could replace all the block tags with p (or div or the element that you want), by indicating it on the regular expression:
$this.html().replace(/(\<\/p\>|\<\/h1\>|\<\/h2\>|\<\/div\>)/gi,"[p]")
As you can see here:
$("#editable").on("input", function() {
$this = $(this);
// replace all closing block tags with special token
$this.html($this.html().replace(/(\<\/p\>|\<\/h1\>|\<\/h2\>|\<\/h3\>|\<\/h4\>|\<\/h5\>|\<\/h6\>|\<\/div\>)/gi,"[p]").replace(/\<br\>/gi,"[br]"));
// remove all the tags
$this.html("<p>" + $this.text().replace(/\[p\]/g,"</div><p>").replace(/\[br\]/g,"<br>") + "</p>");
});
div#editable, div#demo {
border:1px solid gray;
padding:6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div contenteditable="true" id="editable"></div>
<div>
<h3>Demo</h3>
<p>Copy this code and paste it on the editable div above:</p>
<div id="demo">
<p>This <b>is</b> <i>a</i> styled paragraph.</p>
<p> </p>
<p>The <span style="font-weight:bold">above paragraph</span> is empty.</p>
<p>And this is a new paragraph…<br>with a line break!</p>
</div>
</div>
Or on this JSFiddle: http://jsfiddle.net/v5rae96w/1/

What do these symbols mean in html?

I found this code when surfing through jquery tooltip. Please Suggest why we use certain code and what does it mean?
<pre class="prettyprint">
<head>
<script>
$(document).ready(function() {
$('.tooltip').tooltipster({
contentAsHTML: true
});
});
</script>
</head>
<body>
<div class="tooltip" title="&lt;img src=&quot;my- image.png&quot; /&gt; &lt;strong&gt; This text is in bold case !&lt;/strong&gt;">
This div has a tooltip with HTML when you hover over it!
</div>
</body></pre>
The code that your entered is html encoded, it means that with html special characters:
<script>
$(document).ready(function() {
$('.tooltip').tooltipster({
contentAsHTML: true
});
});
</script>
</head>
<body>
<div class="tooltip" title="<img src=my-image.png /> <strong> This text is in bold case!</strong>">
This div has a tooltip with HTML when you hover over it!
</div>
</body></pre>
ISO-8859-1 is the default character in HTML 4.01, please see the list of XML and HTML character for more information.
For instance, "<" is "<" (less-than sign, U+003C)
The code you tried to understand creates tooltip when user put mouse on the div with the text
This div has a tooltip with HTML when you hover over it!
The content of the toolpit is between the title tag, so
<img src=my-image.png /> <strong> This text is in bold case!</strong>
img is to show a picture ant the text between strong... is strong :-)
They are HTML entities, used to show symbols on the page, such as those that are actual html code. So < > as an HTML entity is < > (less than, greater than). © is the copyright symbol etc
< is used for the < symbol. Similary > is used for the > symbol. These are known as HTML entities.
On a side note you can refer this for future reference.
Please refer to this resource for a better understanding http://w3schools.com/HTML/html_entities.asp
Those are html entities.
Reserved characters in HTML must be replaced with character entities.
Characters, not present on your keyboard, can also be replaced by entities.

Fill div with html using javascript/jquery

here is my problem:
I have a div:
<div id="legend"></div>
and I want to fill it, under certain conditions, with this other code:
<p>Showing results....
Key:
<img src="/...."><=1
<img src="/..."><=2
<img src="/..."><=3
<img src="/..."><=4
<img src="/..."><=5
<p>
As you can see this is a legend and the main issue I think is that I have double quotes that cannot be easily included using for instance the solution here:
Fill div with text
Thanks for your help!
By my understanding, you are trying to do something like this:
$("#legend").text("Your HTML here");
To insert HTML, you should use .html(), HOWEVER it would be far more efficient to just use Vanilla JS like so:
document.getElementById('legend').innerHTML = "Your HTML here";
Now, you also mention having problems with double-quotes. Well, there are two possible solutions.
1: Use single-quotes around your string: '<img src="/..." />'
2: Escape the quotes: "<img src=\"/...\" />"
And one more thing: If those newlines are actually in your HTML to insert, you can't have a multi-line string in JavaScript. You have two options here too:
1: Escape the newline:
"<p>\
Hello, world!\
</p>"
2: Concatenate:
"<p>\n"
+"Hello, world!\n"
+"</p>"
Assemble your html code in a variable according to your conditions (which we do not know), then use html() to set it to the element.
var yourHtml = "your html";
$("#legend").html("yourHtml");
As for dealing with the quotes, you can either use single quotes in variable, such as:
var yourHtml = '<img src="/yourimgr.png">';
or you can escape the double quotes:
var yourHtml = "<img src=\"/yourimgr.png\">";
Store your paragraph html in some string
var str= <p>write your complete code here</p>
$('#legend').html(yourconditionSatisfies?str:'')

Categories

Resources