Why JavaScript converts my < into > - javascript

JavaScript converts my < into >. I want to alert it but my message is with encoded marks like ##&*()}{>?>? - how to display it normally but prevent from executing as HTML code?
<span id="ID" onClick="alertIt(this.id);">
<p>Some string with special chars: ~!##&*()}{>?>?>|{">##$#^#$</p>
<p>Why when clicked it gives something like this:</p>
<p>'<br>
Some string with special chars: ~!##&*()}{>?>?>|... and so on
<br>'</p>
</span>
<script type="text/javascript">
function alertIt(ID)
{
var ID = ID;
var content = document.getElementById(ID).innerHTML;
alert(content);
}
</script>

Use innerText instead of innerHTML. http://jsfiddle.net/WVf95/

Your problem is that you use the wrong approach to get the text to display with alert().
Some characters are illegal in HTML text (they are used for HTML tags and entities). innerHTML will make sure that text is properly escaped (i.e. you can see tags and escaped text).
If you want to see tag and text in alert(), there is no solution.
If you want only the text, then you will have to extract it yourself. There is no built-in support for that. It's also not really trivial to implement. I suggest to include jQuery in your page; then you can get the text with:
function alertIt(ID) {
alert($(ID).text());
}

Using textContent instaed of innerHTML or innerText is a solution.

Related

Write <script> or other tags as text in html [duplicate]

I want HTML, for example, <p>, to show show as just that, in plain text, and not interpreted by the browser as an actual tag.
I know JQuery has .html and .text, but how is this done in raw JS?
There are functions like encodeURIComponent that encodes <p> to %3Cp%3E but if I just put that into HTML, it interprets it literally as %3Cp%3E.
So there are also things like > and <, they work but I can't find any JavaScript functions that escapes & unescapes from this.
Is there a correct way to show HTML as text with raw JavaScript?
There's no need to escape the characters. Simply use createTextNode:
var text = document.createTextNode('<p>Stuff</p>');
document.body.appendChild(text);
See a working example here: http://jsfiddle.net/tZ3Xj/.
This is exactly how jQuery does it (line 43 of jQuery 1.5.2):
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
The function used by Prototype looks like a good start:
http://www.prototypejs.org/api/string/escapeHTML
function escapeHTML() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Version more suited to use outside Prototype:
function escapeHTML(html) {
return html.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
You can use aslo innerText from most of DOM elements:
document.getElementById('some').innerText = "There can be <b> even HTML tags </b>";
The tags will not be formatted. You can aslo use \n for new line and more codes (\t, \u2623...). If you want aslo to use fixed-size characters you can use easy <pre> tag.
This is a job for the method createTextNode
var target div = document.getElementById('div1');
targetDiv.appendChild(document.createTextNode('<p>HelloWorld</p>'));
i suggest to use pre tag of html
and you can convert your using this link
e.g if you copy
<p>Hi </p>
it will give you converted code as...
<p>Hi </p>
Just copy and paste above code in pre and it will work fine...

JQuery : Delete span from title tag

Please how can I get a span into title tag i try to use
console.log($('title > span').text());
but it return an empty result. For example I want to get the word beautiful from this code :
<title>lorem epsum dolor <span class="spa">beautiful</span></title>
<title> tag should not include any-other tags inside it.
as stated here https://www.w3.org/TR/html401/struct/global.html#h-7.4.2
Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments).
try this:
$('title span').html()
As Nate mentioned, a span tag is not valid within a title tag. However, if you still need to process it for whatever reason (for instance, a dynamically generated title from a database), you could use a regular expression.
<script>
var titleTag = $('title').text();
var match = titleTag.match(/<span>(.+)<\/span>/);
console.log(match[1]);
</script>

How to render only parts of a string as HTML

I want to render a text as common HTML and parse occurrences of [code] tags that should be output unrendered - with the tags left untouched.
So input like this gets processed accordingly:
<p>render as HTML here</p>
[code]<p>keep tags visible here</p>[/code]
<p>more unescaped text</p>
I've regexed all code-tags but I have no idea how to properly set the text of the element afterwards. If I use jQuery's text() method nothing gets escaped, if I set it with the html() method everything gets rendered and I gained nothing. Can anybody give me a hint here?
Try replacing [code] with <xmp> and [/code] with </xmp> using regex or alike, and then use the jQuery html() function.
Note that <xmp> is technically deprecated in HTML5, but it still seems to work in most browsers. For more information see How to display raw html code in PRE or something like it but without escaping it.
You could replace the [code] and [/code] tags by <pre> and </pre> tags respectively, and then replace the < within the <pre> tags by & lt;
A programmatic solution based on Javascript is as follows
function myfunction(){
//the string 's' probably would be passed as a parameter
var s = "<p>render as HTML here</p>\
[code]<p>keep tags visible here</p>[/code]\
<p>more unescaped text</p>";
//keep everything before [code] as it is
var pre = s.substring(0, s.indexOf('[code]'));
//replace < within code-tags by <
pre += s.substring(s.indexOf('[code]'), s.indexOf('[/code]'))
.replace(new RegExp('<', 'g'),'<');
//concatenate the remaining text
pre += s.substring(s.indexOf('[/code]'), s.length);
pre = pre.replace('[code]', '<pre>');
pre = pre.replace('[/code]', '</pre>');
//pre can be set as some element's innerHTML
return pre;
}
I would NOT recommend the accepted answer by Andreas at all, because the <xmp> tag has been deprecated and browser support is totally unreliable.
It's much better to replace the [code] and [/code] tags by <pre> and </pre> tags respectively, as raghav710 suggested.
He's also right about replacing the < character with <, but that's actually not the only character you should replace. In fact, you should replace character that's a special character in HTML with corresponding HTML entities.
Here's how you replace a character with its corresponding HTML entity :
var chr = ['&#', chr.charCodeAt(), ';'].join('');
You can replace the [code]...[/code] with a placeholder element. And then $.parseHTML() the string with the placeholders. Then you can insert the code into the placeholder using .text(). The entire thing can then be inserted to the document (run below or in JSFiddle).
var str = "<div><b>parsed</b>[code]<b>not parsed</b>[/code]</div>";
var placeholder = "<div id='code-placeholder-1' style='background-color: gray'></div>";
var codepat = /\[code\](.*)\[\/code\]/;
var code = codepat.exec(str)[1];
var s = str.replace(codepat, placeholder);
s = $.parseHTML(s);
$(s).find("#code-placeholder-1").text(code);
$("#blah").html(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text
<div id="blah">place holder</div>
Around
The code above will need some modifications if you have multiple [code] blocks, you will need to generate a unique placeholder id for each code block.
If you may be inserting untrusted structure code, would highly recommend using large random number for the placeholder id to prevent a malicious user from hijacking the placeholder id.

Add code examples on your page with Javascript

I have a html code inside string
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
And I want to put this inside textarea, but when I do it, the result is:
- bonus for each year
It simply deletes all things inside the html tags. I just want to show all the code inside the string. I already tried <xmp>,<pre>, but none of them worked.
Thanks for any help.
EDIT.
Code with which I input data from the array to the textarea/code.
$('body').append('<code class="code_text"></code>');
for(var i=0; i<tag_list.length; i++){
var string='';
string+='---------------------------------------------------------------------------------\n';
string+='tag: '+tag_list[i][0]+'\n';
string+='nazwa_pl '+tag_list[i][1]+'\n';
string+='nazwa_eng '+tag_list[i][2]+'\n';
string+='tekst_pl '+tag_list[i][3]+'\n';
string+='tekst_eng '+tag_list[i][4]+'\n';
string+='\n\n\n';
$('.code_text').append(string);
}
I tried this using jsfiddle:
HTML
<textarea id="code"></textarea>
JavaScript
$(document).ready(function() {
var string_eng = '';
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
$("#code").html(string_eng);
});
Output (contained in textarea)
<b>Year Bonus</b> - bonus for each year</br></br>
Try it here: http://jsfiddle.net/UH53y/
It does not omit values held within tags, however if you were expecting the <b></b> tags to render as bold within the textarea, or the <br /> tags to render as line breaks, this wont happen either. textarea does not support formatting.
See this question for more information: HTML : How to retain formatting in textarea?
It's because you're using the jQuery .append method which seems to parse the string and insert it afterwards. I don't know jQuery at all, so there might be another special jQuery method, but here is a simple fix:
$('.code_text').append(document.createTextNode(string));
Edit:
I just read and tried the answer of Salman A. The "special jQuery method" exists and he used it. You can use this:
$('.code_text').text(string);

Preserve html characters within google-prettified pre element?

I'm attempted to include syntax highlighting into my Tumblr blog by means of google-prettify and some jQuery.
Google-prettify requires the <pre> element to have a class of prettyprint in order for it to highlight the syntax, but since I'm using markdown to create my Tumblr posts, I can't add a class to my <pre> elements.
My solution is to use this jQuery snippet to append the prettyprint class to the <pre> element:
<script type='text/javascript'>
$(document).ready(function() {
$('pre').addClass('prettyprint');
prettyPrint();
});
</script>
This is working fine, but I'd like to be able to copy and paste the code that I want to show on my Tumblr, instead of converting all < to < and > to > every time I want to post a code snippet.
Using jQuery, I'd like to replace all the < and > with their corresponding html code, but only within the pre element. This however, might have some problems, as it would need to replace all of those before the code is prettified.
Could I append the new class, replace the tags, and then call prettyPrint(); to intialize everything? Or should I just change the html characters into htmlentities by hand before posting the code?
Little update:
This script works with changing the < and >, except with <body>,<html>, and <head>...
<script type='text/javascript'>
$(function() {
var $pre = $('pre');
$pre.html($pre.html().replace(/</g, 'f').replace(/>/g, 'l'));
});
</script>
<pre>
<html></html>
<body></body>
<head><head>
<i></i>
</pre>
Note: I used f as the replacement just to test the code.
If you first replace all the ampersands with entities, and then the less than signs, you can use the returned string as a text-node in a <pre>, or any block container with its white-space set to 'pre'.
function stripX(str){
return str.replace(/\&(?!(\w+;))/g, '&').replace(/</g, '<');
}

Categories

Resources