Hello I am trying to store some html output in a JS var to output it to the page using "getElementById"...
The problem I am having is with single quotes versus double quotes and when to wrap them within each other...
here is my code:
var buttonOutput1="<br/>";
var buttonOutput2="<button onclick="DealCard('player')">Hit</button>";
var buttonOutput5=buttonOutput1+buttonOutput2;
document.getElementById('buttonArea').innerHTML = buttonOutput5;
I know a little about this, I know you can enclose something within single quotes and then enclose that within double quotes and it all works fine.
But because I want to store it all in a variable, I need to enclose it all in a third set of quotes and so therein is my problem.
So just stuck on what I should do here, wondering if anyone can help on this.
Thanks, G
**** My solution 12:51PM EST ****
Was able figure this out by breaking it into pieces:
var buttonOutput1="<br/>";
var buttonOutput2a="DealCard('player')";
var buttonOutput2b='<button onclick="' + buttonOutput2a + '">Hit
Me</button>';
var buttonOutput5=buttonOutput1+buttonOutput2b;
document.getElementById('buttonArea').innerHTML = buttonOutput5;
You can create a DOM node using create Element (DOM Level 2) and attach a function to the onclick attribute.
var domNode = document.createElement('button');
domNode.innerHTML = 'Click me';
domNode.onclick = function() {
alert("hello world")
};
document.getElementById('hook').appendChild(domNode);
<div id="hook"></div>
Related
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'm having a little difficulty trying to switch 2 elements around with Jquery when they are inside a string variable.
eg:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
What I would like is to switch the two classes around, making "anotherTest" be infront of "test".
What I've tried so far is:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
var div1 = myString.filter('.test');
var div2 = myString.filter('.anotherTest');
var tdiv1 = div1.clone();
var tdiv2 = div2.clone();
myMessage = div1.replaceWith(tdiv2);
myMessage = div2.replaceWith(tdiv1);
However I receive the following error
t.replace is not a function
I was wondering how I would be able to achieve to switch the two divs around while still stored inside the variable before displaying it to the user?
You're making things harder on yourself by adding the constraint that this needs to be done by direct string manipulation. HTML is meant to be rendered into the DOM -- and since that's a "document object model" it stands to reason it's better-suited for modelling your document as objects.
jQuery may seem a bit old-hat, but its whole purpose is to make querying the DOM easier, so it works well here. All you need to do is parse the string, query the node you want to move, and insert it before the element you want it in front of. You can get the HTML back using $.fn.html(), or you could just leave as an element if you're going to insert it somewhere on your page.
var $el = $(myString);
$('.anotherTest', $el).insertBefore($('.test', $el));
var myMessage = $el.html();
jsfiddle here
Try this one. Just split the string by "</div>", it will make an array of splited contents, then re-add "</div>" to each splited string (this will be consumed in the process of splitting).
Then reassemble.
https://jsfiddle.net/8a4wgn7k/
var myString = "<div class='test'>My test</div><div class='anotherTest'> the other test</div>";
var res = myString.split("</div>");
res[0] +="</div>";
res[1] +="</div>";
var switchedString=res[1]+res[0]
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 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 create an in memory div:
var video_div = document.createElement('div');
video_div.className = "vidinfo-inline";
In essence I have some variables:
var key = "data-video-srcs";
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
And I use jquery to add that data attribute to the div:
$(video_div).attr(key, value);
Here is my problem. After doing that I get this:
<div class="vidinfo-inline" data-video-srcs="{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}"></div>
And that doesn't work putting that json in there. It has to be in single quotes. It has to look like this:
<div class="vidinfo-inline" data-video-srcs='{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}'></div>
As later on I do something like this:
var video_srcs = $('.vidinfo-inline').data('video-srcs');
And that won't work unless the json is in single quotes.
Does anyone have any ideas?
EDIT:
According to jquery: http://api.jquery.com/data/#data-html5
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.
Thus I can't escape the double quotes, it has to be inside single quotes. I have a work around and I'll post that as an answer unless someone else has a better answer.
I have a workaround. And if anyone has a better solution, I'd love to see it.
I wrote a replace method:
var fixJson = function(str) {
return String(str)
.replace(/"{/g, "'{")
.replace(/}"/g, "}'");
};
So basically I send the html into this function and insert it into the DOM.
For example:
var html = htmlUnescape($('#temp_container').html());
html = fixJson(html);
I realize that has some code smell to it. I mean, going through everything on that element just to fix the double quotes to single quotes stinks. But for lack of other options or ideas, it works. :\
Replace the double quotes with HTML entities:
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
# Naive approach:
value = value.replace('&', '&').replace('"', '"');
# Using jQuery:
var $tmp = jQuery('<div></div>');
value = $tmp.text(value).html();
// Then store it as normal