jQuery 'HTML function doesn't work with special characters - javascript

I am trying to pass the string "{<A+_2OF3_MSF}" to jQuery's HTML function. It doesn't work because of special character <. I tried encoding/escaping an HTML tag using this escapeHtml function, but I am facing another issue after that.
var escapeHtml = function(theString) {
return theString.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
};
It appends HTML-encoded string as text, not as HTML. I saw the below Stack Overflow post, but then it suggests to decode it after encoding. If I do that I am back to square one.
Appending HTML-encoded string as HTML, not as text
I have created a fiddle:
https://jsfiddle.net/1aktfzm8/

You need to use .text() instead of .html()
$(document).ready(function(){
$("button").click(function(){
$("p").html("<span id=\"span\"> {A+_\"2OF3_MSF\"} </span>");
$('#span').text();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

This code is working normally: https://jsfiddle.net/kilotonna/eg4be1gr/1/
$(document).ready(function(){
$("button").click(function(){
$("p").html("{<A+_2OF3_MSF}".replace(/</g, '<'));
});
});

Related

Understanding the specifics of the jquery text() with HTML Entities

I have trouble understanding the specific of the jquery text() function in combination with HTML Entities. It seems to be that the text() function converts special HTML Entities back to normal characters. In particular, I am unsure how this code snippet behaves:
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
since the output seems to be a string where HTML Entities are unescaped. Does this mean that the text() function unescapes HTML Entites?
EDIT/FOLLOW UP:
Since text() seems to only return the real text content, I have trouble understanding this code snippet, which returns an unescaped . If text() returns the escaped string, why does the html function return a formatted one?
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
$("#test").html(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
text() isn't doing anything special. The browser itself translates entities into their rendered characters when it parses the original HTML. So when you write <h1> in the HTML, the browser converts this to the literal string <h1>. .text() simply returns this text.
When you then use .html(), this causes the string to be parsed as HTML, so <h1> is rendered as an HTML tag, and you get the formatted result.
If you look at the source you'll see that it is pulling out the textContent from elements.
https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
Some documentation of what textContent is:
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
//https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
console.log($("#test").get(0).textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>

Remove style attributes from string

I'm trying to remove all style attributes from a string (and not an object), in JavaScript or jQuery.
Example
var html = "<p style="color:red">my text</p>";
And I want to obtain this:
<p>my text</p>
Is it possible to do it without calling the functions that we can call on objects (as removeAttr)?
Thanks
If you are not looking to use JavaScript or jQuery objects, have you tried using regular expressions?
This answer to a previous question shows a php version that can be adapted to JavaScript using the replace function.
See if this helps.
$("button").click(function() {
$("p").removeAttr("style");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="color:red">my text</p>
<button>Remove the style attribute from all p elements</button>

how to find first level of child tag in jquery

I have XML like below
<parent id="parent">
<body>
body text<body>hello</body>
</body>
</parent>
as shown in above code it have parent tag where there is only body tag should available, but there is some text in body tag with tag again.
so if i use
$('#parent').find('body').text();
it show output as
body text hello
but i want the output exactly like
body text<body>hello</body>
how should i do? If again there are more than one body tag are written in first body tag it should be treated as only text. not as tag.
Use html instead:
$('#parent').find('> body').html();
$('#parent').find('body:first').html();
HTML
<body>and another text followed by <div class="someText"></div>Some text followed by</body>
JQuery
var texts = $('.someText, body').map(function(){
return this.previousSibling.nodeValue
});
alert(texts[0]); // "Some text followed by "
alert(texts[1]); // " and another text followed by "
DEMO
You can use some DOM Traversing:
$('#parent').find('body').first().html();

Cannot get the hidden tag value

Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.

How to copy newline characters from HTML div to textarea in jQuery?

Consider the following HTML page fragment:
<div id='myDiv'>
Line 1.<br />
Line 2<br />
These are &ltspecial> characters & must be escaped !##><>
</div>
<input type='button' value='click' id='myButton' />
<textarea id='myTextArea'></textarea>
<script>
$(document).ready(function () {
$('#myButton').click(function () {
var text = $('#myDiv').text();
$('#myTextArea').val(text);
});
});
</script>
First, there is a div element with id myDiv. It contains some text similar to what might be retrieved form a SQL database at runtime in my production web site.
Next, there is a button and a textarea. I want the text in myDiv to appear in the textarea when the button is clicked.
However, using the code I provided, the line-breaks are stripped out. What can I do about this, taking into consideration that escaping special characters is absolutely non-negotiable?
Your code works great for me in both Firefox and Chrome: http://jsfiddle.net/jYjRc/
However, if you have a client that doesn't do what you want, replace <br>s with newline characters.
Edit: Tested in IE7 and the code breaks. So I updated the fiddle with my suggestion: http://jsfiddle.net/jYjRc/1/
Do your HTML like so:
<div id='myDiv'><pre>
Line 1.
Line 2
These are &ltspecial> characters & must be escaped !##><>
</pre></div>
And now .text() will return the text exactly as you specify it in the <pre> tag, even in IE.

Categories