I have a string coming from a XML (which I can't edit) and I'd like to print it trough an alert in javascript.
Example of my string:
This is à string
And I need to print in an alert:
This is à string
is there a js html decode?
you could put the string in a dom element and read it out again, even without jquery:
https://stackoverflow.com/a/3700369/1986499
Edit by recent demand to include some code from another SO answer:
var div = document.createElement('div');
div.innerHTML = encoded;
var decoded = div.firstChild.nodeValue;
var encoded = "This is à string";
var decoded = $("<div/>").html(encoded).text();
alert(decoded);
I'm just a tiny bit late, but just in case anyone else finds this via Google (like I did), I thought I'd improve upon Imperative's answer.
function showbullet() {
var tempelement = document.createElement('div');
tempelement.innerHTML = "•";
alert("Here, have a bullet!\n" + tempelement.innerHTML);
}
showbullet();
I've tested this and confirmed it works in Chrome/43.0.2357.130 m; Firefox/32.0.1; Internet Explorer/9.0.8112.16421. There's no need to go mucking about with nodeValue's and what not; the entity will be replaced with it's associated character as soon as the assignment is complete. (Note, however, that doing alert(tempelement.innerHTML="•"); does not work in any of the browsers I tested!)
Related
I have a button that runs a batch file, which the code is:
<button onclick="window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat')">Continue</button>
I can put that directly in the HTML file and it works just fine, however I am inserting this specific piece of code into the file via output.innerHTML and it's not working. I assume the "/" have to be changed, but I have also tried:
<button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>...which also does not work. Any ideas what I'm missing here?
JavaScript I am using:
function novpn() {
var output = document.getElementById("main");
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br><button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>";
output.innerHTML = sentence;
}
You have ' nested within '.
The easy way out is to use ", but escaped, as the inner quote. Then go back to the original URL (with forward slashes):
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br>" +
"<button onclick='window.open(\"file:///C:/Users/gthornbu/Desktop/TEST/test.bat\")'>Continue</button>";
You can declare strings with ", ' characters. If you have to call a function with parameter in html attribute, declaration may become a problem.
You can resolve this with escape character. \
It will escape behaving the character caused. You must add before it.
var str = "string";
var str2 = \""string\"";
str === str2 // true
In your case, you can do it like this.
output.innerHTML = '<button onclick="window.open(\'file:///C:/Users/gthornbu/Desktop/TEST/test.bat\')">Continue</button>'
Working JS Fiddle
http://jsfiddle.net/ebilgin/wLe04pwg/
Nesting html markup and javascript code in strings can become an headache to get the single and double quotes right and escaped where needed. Although it allows for some rather rapid application development if you need to maintain this later you might give this solution try.
Instead of figuring out which quote needed to go where I recreated your target html in vanilla javascript commands to create the same result by using different functions and wiring it all together.
I used the document.createElement function to create the html elements needed and the appendChild function to add them to the main element. The button get the function for opening the window attached to the onclick event.
function novpn() {
var output = document.getElementById("main");
// create the h3 elelement and its content
var h3 = document.createElement('h3');
h3.innerHTML = "You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.";
// the br
var br = document.createElement('br');
// create the button
var button = document.createElement('button');
button.innerHTML = "Continue";
// the onclick handler can now become
// a normal javascript function
button.onclick = function() {
window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat');
};
// add all created elements to main
output.appendChild(h3);
output.appendChild(br);
output.appendChild(button);
}
// start
novpn();
<div id='main'>
<div>title</div>
</div>
I am tring to add some content after the original content, but the new content will cover the original content everytime...What wrong in this case? (Sorry for my terrible english...)
var originaltext = document.getElementById("id").innerHTML;
document.getElementById("id").innerHTML = originaltext + "newtext";
One more thing,I tried to use alert to show the "originalltext", but it have nothing to show.
alert(originaltext);
your code looks ok to me. I made a jsfiddle for you just to see that it works http://jsfiddle.net/3mqsLweo/
var myElement = document.getElementById('test');
var originalText = myElement.innerHTML.toString();
myElement.innerHTML = originalText+" new text";
check that you only have one element with the id "cartzone"
A simple and fast way to do this is to concatenate the old value with the new.
document.getElementById('myid').innerHTML += " my new text here"
this problem usually occurs when the rest of your code is poorly written and contains errors or when the same ID is used several times.
I had the same problems in the past.
you have tow options:
check the rest of your code (validate)
use jQuery - I don't know how, but it works every time.
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
I am converting standard JavaScript over to jQuery for cross browser compatibility. I just want to know how will this be written in jQuery? In other words how do I find the first element?
var x = content.getElementsByTagName("title")[0].firstChild.data;
I have tried the following:
var content = $.parseXML(zipEntry1.data);
content = $(content);
var x = content.find("title").first().val();
and
var content = $.parseXML(zipEntry1.data);
content = $(content);
var x = content.find("title")[0].val();
But none of those work. What would be the correct way?
EDIT:
Here is some additional info. I am writing a Epub reader. The file I am parsing is content.opf within the Epub specification. Here is an extract:
<metadata>
<dc:rights>Public domain in the USA.</dc:rights>
<dc:identifier id="id" opf:scheme="URI">http://www.gutenberg.org/ebooks/6130</dc:identifier>
<dc:contributor opf:file-as="Buckley, Theodore Alois" opf:role="ann">Theodore Alois Buckley</dc:contributor>
<dc:creator opf:file-as="Homer">Homer</dc:creator>
<dc:contributor opf:file-as="Pope, Alexander" opf:role="trl">Alexander Pope</dc:contributor>
<dc:title>The Iliad</dc:title>
<dc:language xsi:type="dcterms:RFC4646">en</dc:language>
<dc:subject>Classical literature</dc:subject>
<dc:subject>Epic poetry, Greek -- Translations into English</dc:subject>
<dc:subject>Achilles (Greek mythology) -- Poetry</dc:subject>
<dc:subject>Trojan War -- Poetry</dc:subject>
<dc:date opf:event="publication">2004-07-01</dc:date>
<dc:date opf:event="conversion">2012-10-31T19:41:56.338029+00:00</dc:date>
<dc:source>http://www.gutenberg.org/files/6130/6130-h/6130-h.html</dc:source>
I can get the author and title with this, but it only works in Chrome:
content.find('creator:first').text();
content.find('title:first').text();
Version works in Firefox and Chrome:
content.find("package").attr("version");
And I have not yet got the publication date. This is what I tried:
content.find('[event="publication"]').val();
If you need to get the text content of the first title use this:
$('title:first', content).text();
However jQuery in Firefox require namespace to be specified as well:
var ff = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
$((ff ? 'dc\\:' : '') + 'title:first', content).text();
Working example: http://jsbin.com/enayex/5/edit
If you know the element type then this can be easy. Let us assume that we are dealing with divs, then do this:
$('div').first().html("<p>I found you</p>");
something like this maybe?
var x = content.find('title:first').html()
or
var x = content.find('title:first').text();
So I have a string like this
string = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>"
How could I parse the string in Javascript or JQuery to pull out the "Notes" of either user 1 or user 2.
So I'll have a variable like this:
variable = user;
printout notes of user.
You mean an XML like string, not a HTML like string. jQuery has a lovely XML parser for that http://api.jquery.com/jQuery.parseXML/
to identify the notes of user1 or user2 you need to change your xml a bit
string = "<user>username 1<notes id='user1'>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>"
notice that i added id=user1
alert($(string).find("notes[id='user1']").text());
here is the fiddle http://jsfiddle.net/Qa5sP/
EDIT after the -1 :(
No, jQuery selectors do not parse XML.
This may appear to work at times, but it's invalid and browser-dependent.
So, here is the parseXML way:
xmlDoc = $.parseXML(string),
$xml = $(xmlDoc),
$title = $xml.find("notes[id='user1']").text();
alert($title);
Live demo.
Here's a JSFiddle. It's simple to do using jQuery if you are using HTML-parsible XML (as seen above).
string = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>";
var node = $("<div>" + string + "</div>");
alert(node.find('notes').text());
node.attachTo(document.body); //append to dom?
I would rather go with this approach.
var xml = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>";
function FindNotesByUserName(uName) {
var node = $('<div/>').html(xml);
return node.find(":contains('" + uName + "')").closest("user").find("notes").text();
}
var desiredNotes = FindNotesByUserName("username 2");
N.B: This is a minor alteration of what ghayes did. Just to meet OP requirement.