Good day! Newbie here. I just want to know if it's possible to change the whole content of an html using javascript? I got some codes here. (not mine but whoever did this, thank you so much!) I don't know where to put/insert all the codes of the new layout like when you click a button then the whole content will change. Thank you very much for helping me.
<script language="Javascript">
<!--
var newContent='<html><head><script language="Javascript">function Hi()</script></head><body onload="Hi();"><p id="p">hello</p></body></html>';
function ReplaceContent(NC) {
document.write(NC);
document.close();
}
function Hi() {
ReplaceContent(newContent);
}
-->
</script>
The easiest way to do this is with jQuery.
function insertHtml()
{
var newHtml = '<div><span>Hello World</span></div>';
$('body').html(newHtml);
}
Something like that will replace the entire contents of body with newHtml. You can also do this with pure javascript using the .innerHtml property but jQuery has many advantages.
EDIT: If you want to add something to the DOM rather than replacing the entire thing, use
$('body').append(newHtml)
instead. This will add the content to the end of the body. This is very often used for things like adding rows to a table.
Yes it is possible but this code is not valid unless you remove the comment tags however don't use the document.write() after page load unless you want to overwrite everything in page including the script
Related
I am calling a .html page(say A.html, which is dynamically created by another software each time a request is made) inside another webpage (say B.html). I am doing this by using the .load() function. Everything works fine but the problem is I donot want the so many "br" tags (empty tags) present at the end of A.html into B.html. Is there any way to avoid fetching those "br" tags into B.html? Any suggestion would be of great help. Thank you in advance.
You can't avoid loading part of a file when you are just accessing it.
The best option would be to simply remove the extra <br> tags from the document to begin with. There is probably a better way to accomplish whatever they are attempting to accomplish.
With some server-side scripting, it could be possible to strip them automatically when you load it, but would probably be pretty bothersome to do.
Instead, if you can't remove the <br> elements for some reason, what might be easier, if you are just dealing with a handful of <br> tags would be to simply strip them out.
Since you mention using the load() function, I'm guessing you are using jQuery.
If that's the case, something like this would cleanly strip out any extra <br> tags from the end of the document.
Here is a JSfiddle which will do it: http://jsfiddle.net/dMJ2F/
var html = "<p>A</p><br><p>B</p><br><p>C</p><br><br /><br/>";
var $html = $('<div>').append(html);
var $br;
while (($br = $html.find('br:last-child')).length > 0) {
$br.remove();
}
$('p').text($html.html());
Basically, throw the loaded stuff in to a div (in memory), then loop through and remove each <br> at the end until there aren't any. You could use regex to do this as well, but it runs a few risks that this jQuery method doesn't.
You shout delete the br-tags in your A.html.
Substitute them by changing the class .sequence with marging-top:30px
And have an other value in your B.html-file.
You also can run this:
$('br', '.sequence').remove();
in the load-function. It will strip all br-tags.
You can't avoid fetching a part of your page, but you CAN fetch only a part of it.
According to the jQuery docs, you can call load like this:
$("#result").load("urlorpage #form-id");
That way, you only load the form html inside the result element.
I have this script generated by wordpress plugin:
<script type='text/javascript'>
if (typeof(jQuery)=="function") {
(function($) {
$.fn.fitVids=function(){}})(jQuery)
};
jwplayer('jwplayer-0').setup({
"aspectratio":null,
"width":604,
"height":410,
"skin":"beelden",
"primary":"html5",
"advertising":{
"client":"vast",
"tag":"http://vasttag"
},
"sharing":{},
"image":"http://i1.ytimg.com/vi/image/0.jpg",
"file":"http://www.youtube.com/watch?v=hgfakjhs"
});
</script>
I simply want add this line:
,"position":"post"
after:
"http://vasttag"
I can't edit the plugin, so is there a way to do it with javascript?
Sorry for my bad english.
Please help me!
Thanks!
Edit: This is the plugin file that generates the player:
link
if anyone knows how to add that parameter I would be very grateful :)
Edit 2:
I solved adding that parameter directly in the database, in wp-option table at jwp6_player_config_2 option name. If you know better solution let me know, thanks.
Due to what the script does (it creates a new jwPlayer as soon as the script is encountered) and the fact that there seems to be no method in the jwPlayer API to edit a players settings, it is impossible to change your script as you want.
The only solution is to edit the script at its source.
I dont think you can do that using javascript.We generally use javascript to do changes in DOM and not in javascript itself.You can do one thing that you create.
<script>
if(typeof(jQuery)=="function")
{
(function($){$.fn.fitVids=function(){}})(jQuery)};
jwplayer('jwplayer-0').setup({"aspectratio":null,"width":604,"height":410,"skin":"beelden","primary":"html5","advertising":{"client":"vast",,"position":"post","tag":"http://vasttag"},"sharing":{},"image":"http://i1.ytimg.com/vi/image/0.jpg","file":"http://www.youtube.com/watch?v=hgfakjhs"});
</script>
and append it somewhere in DOM using javascript or jquery.
More better solution: Just edit the script added by plugin.It is the best approach.
One thing you can always do is use our JavaScript API - http://www.longtailvideo.com/support/jw-player/28851/javascript-api-reference
To make the VAST tag play after the video is complete. Just put this script block after the shortcode on your post:
<script>
jwplayer().onComplete(function(){jwplayer().playAd('your_ad_tag');});
</script>
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.
Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.
So ultimately, what I need to do is come up with a jQuery statement that replaces
<br><br clear=all><br>
with
<br />
I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?
Thanks in advance for any help!
Use the Next Adjacent Selector (+):
$("br+br").remove(); //Removes all <br> tags in front of another
jsFiddle demo
Assuming they are in the exact format you gave, you can do this:
var br = $('br[clear="all"]');
br.attr('clear', '');
br.prev('br').remove();
br.next('br').remove();
You can play with selector attributes, not inside the onload but inside the jquery ready (http://api.jquery.com/ready/)
$('br[clear=all]').remove();
more details on selector attribute:http://api.jquery.com/attribute-equals-selector/
Why donn`t just replace the html of the RSS HTML container:
yourContainerElem.innerHTML = yourContainerElem.innerHTML.replace(/<br><br clear=all><br>/gi, '<br />');
To remove all but one:
$('br,[clear!="all"]').remove()
Then to remove the 'clear=all':
$('br').removeAttribute('clear')
You better do this with regexps not with jquery. Simplest example:
string.replace('<br><br clear=all><br>', '<br />')
Is it possible to get in some way the original HTML source without the changes made by the processed Javascript? For example, if I do:
<div id="test">
<script type="text/javascript">document.write("hello");</script>
</div>
If I do:
alert(document.getElementById('test').innerHTML);
it shows:
<script type="text/javascript">document.write("hello");</script>hello
In simple terms, I would like the alert to show only:
<script type="text/javascript">document.write("hello");</script>
without the final hello (the result of the processed script).
I don't think there's a simple solution to just "grab original source" as it'll have to be something that's supplied by the browser. But, if you are only interested in doing this for a section of the page, then I have a workaround for you.
You can wrap the section of interest inside a "frozen" script:
<script id="frozen" type="text/x-frozen-html">
The type attribute I just made up, but it will force the browser to ignore everything inside it. You then add another script tag (proper javascript this time) immediately after this one - the "thawing" script. This thawing script will get the frozen script by ID, grab the text inside it, and do a document.write to add the actual contents to the page. Whenever you need the original source, it's still captured as text inside the frozen script.
And there you have it. The downside is that I wouldn't use this for the whole page... (SEO, syntax highlighting, performance...) but it's quite acceptable if you have a special requirement on part of a page.
Edit: Here is some sample code. Also, as #FlashXSFX correctly pointed out, any script tags within the frozen script will need to be escaped. So in this simple example, I'll make up a <x-script> tag for this purpose.
<script id="frozen" type="text/x-frozen-html">
<div id="test">
<x-script type="text/javascript">document.write("hello");</x-script>
</div>
</script>
<script type="text/javascript">
// Grab contents of frozen script and replace `x-script` with `script`
function getSource() {
return document.getElementById("frozen")
.innerHTML.replace(/x-script/gi, "script");
}
// Write it to the document so it actually executes
document.write(getSource());
</script>
Now whenever you need the source:
alert(getSource());
See the demo: http://jsbin.com/uyica3/edit
A simple way is to fetch it form the server again. It will be in the cache most probably. Here is my solution using jQuery.get(). It takes the original uri of the page and loads the data with an ajax call:
$.get(document.location.href, function(data,status,jq) {console.log(data);})
This will print the original code without any javascript. It does not do any error handling!
If don't want to use jQuery to fetch the source, consult the answer to this question: How to make an ajax call without jquery?
Could you send an Ajax request to the same page you're currently on and use the result as your original HTML? This is foolproof given the right conditions, since you are literally getting the original HTML document. However, this won't work if the page changes on every request (with dynamic content), or if, for whatever reason, you cannot make a request to that specific page.
Brute force approach
var orig = document.getElementById("test").innerHTML;
alert(orig.replace(/<\/script>[.\n\r]*.*/i,"</script>"));
EDIT:
This could be better
var orig = document.getElementById("test").innerHTML + "<<>>";
alert(orig.replace( /<\/script>[^(<<>>)]+<<>>/i, "<\/script>"));
If you override document.write to add some identifiers at the beginning and end of everything written to the document by the script, you will be able to remove those writes with a regular expression.
Here's what I came up with:
<script type="text/javascript" language="javascript">
var docWrite = document.write;
document.write = myDocWrite;
function myDocWrite(wrt) {
docWrite.apply(document, ['<!--docwrite-->' + wrt + '<!--/docwrite-->']);
}
</script>
Added your example somewhere in the page after the initial script:
<div id="test">
<script type="text/javascript"> document.write("hello");</script>
</div>
Then I used this to alert what was inside:
var regEx = /<!--docwrite-->(.*?)<!--\/docwrite-->/gm;
alert(document.getElementById('test').innerHTML.replace(regEx, ''));
If you want the pristine document, you'll need to fetch it again. There's no way around that. If it weren't for the document.write() (or similar code that would run during the load process) you could load the original document's innerHTML into memory on load/domready, before you modify it.
I can't think of a solution that would work the way you're asking. The only code that Javascript has access to is via the DOM, which only contains the result after the page has been processed.
The closest I can think of to achieve what you want is to use Ajax to download a fresh copy of the raw HTML for your page into a Javascript string, at which point since it's a string you can do whatever you like with it, including displaying it in an alert box.
A tricky way is using <style> tag for template. So that you do not need rename x-script any more.
console.log(document.getElementById('test').innerHTML);
<style id="test" type="text/html+template">
<script type="text/javascript">document.write("hello");</script>
</style>
But I do not like this ugly solution.
I think you want to traverse the DOM nodes:
var childNodes = document.getElementById('test').childNodes, i, output = [];
for (i = 0; i < childNodes.length; i++)
if (childNodes[i].nodeName == "SCRIPT")
output.push(childNodes[i].innerHTML);
return output.join('');
Using a ajax request I want to change content of my div.
<div id="d1">202</div>
So I want to change the content to a different number.
$('d1').InnerText???
Also, say I wanted to increment the number, how could I do that? Do I have to convert to int?
$("#di").html('My New Text');
Check out the jQuery documentation.
If you wanted to increment the number, you would do
var theint = parseInt($("#di").html(),10)
theint++;
$("#di").html(theint);
P.S. Not sure if it was a typo or not, but you need to include the # in your selector to let jQuery know you are looking for an element with an ID of di. Maybe if you come from prototype you do not expect this, just letting you know.
This would changed the inner text of your HTML element.
$('#d1').text(parseInt(requestResponse)++);
Unless you're embedding html like <b>blah</b> I'd suggest using $("#di").text() as it'll automatically escape things like <, > and &, whereas .html() will not.
Use the text function:
$("#d1").text($("#d1").text() + 1);
$('#d1').html("Html here");
jQuery('#d1').html("Hello World");
if your value is a pure text (like 'test') you could use the text() method as well. like this:
$('#d1').text('test'); Or $('#d1').html('test');
anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:
$(document).ready(
function() {
$('#d1').text('test');
}
);
this way the script executes after the HTML of the div is parsed by the browser.
$("#div1").innerHTML="your text goes here..";