I am trying to replace the document.write() function in Javascript. Not completely sure how to do, as I don't know which element to write the HTML to.
Currently, the code javascript code is inserted to my page using:
<script src="//example.com/file.js" type="text/javascript"></script>
The file contains a document.write() function:
document.write('<h2>Testing HTML</h2>Hello');
However, as document.write() can't be called asynchronously, I need to figure out another solution. I can not use getElementsById() or something like that, because I simply don't know any element on the target website.
I want the HTML code to be inserted exactly on the position that the script tag is.
Any suggestions?
Try this:
<script src="//example.com/file.js" type="text/javascript" id="myScript"></script>
And in the javascript:
var script = document.getElementById('myScript');
script.outerHTML += '<h2>Testing HTML</h2>Hello';
As you don't have the script ID, try this:
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
// Async
setTimeout(function() {
script.outerHTML += '<h2>Testing HTML</h2>Hello';
}, 2000);
First you will need to create an element to add your HTML to, if you already have your HTML in a variable, that's great, use it instead of yourElement below.
// Create an element, add HTML to it
var yourElement = document.createElement ('div');
yourElement.innerHTML = '<div>Test</div>';
Then, you will get the current JavaScript tag...
// Get the current script tag (meaning yours)
var scripts = document.getElementsByTagName ('script');
var thisScript = scripts[scripts.length - 1]
And you will insert your HTML element before this tag...
// Insert your element before current script tag
thisScript.parentNode.insertBefore (yourElement, thisScript);
You can also insert your HTML element after the JavaScript tag as well.
Credit: This code was inspired by HashOver: tildehash.com/hashover/hashover.js
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How may I reference the script tag that loaded the currently-executing script?
I am trying to make a javascript function that includes a html doc on a page via AJAX, as a way of making a PHP-esque include() with no serverside interaction. I want the script to include the file at the location on the page the function is called from. Here's my function (assuming ajax is a valid xmlhttp object):
function include(src, elem){
ajax.open('GET', src, false);
ajax.send(null);
elem.innerHTML = ajax.responseText;
}
So this would print the contents of "src.html" in the div when it is clicked:
<div onclick="include('src.html', this);"> </div>
But I want it to load when the page does. Considering there is no onload event for divs I have to include the script in the div, which is fine:
<div id=write>
<script>include('src.html', this);</script>
</div>
But then the script has no reference to the div it is called from. Sure I could put an id on the div and pass that to the function, but I don't want to. I want to be able to call this from any unidentified element. Any ideas?
You could change your div (or other element(s)) to use a data- attribute to specify what script to run:
<div data-include="src.html"></div>
And then run a script onload of the page (or in a script block just before the closing </body> tag) that finds all elements with that attribute.
var elements = document.querySelectorAll("[data-include]");
for (var i = 0; i < elements.length; i++)
include(elements[i].getAttribute("data-include"), elements[i]);
Here's a demo of the above (with a dummy include() function that just puts the required source url string in the element rather than doing Ajax, but it shows the elements are selected correctly): http://jsfiddle.net/nnnnnn/gm2LN/
For simplicity I've used querySelectorAll() to select the elements, but note that it isn't supported in IE7 and older. But obviously you can substitute whatever other element selection method you like if you want or need to support older browsers.
Here:
<div id=write>
<script>include('src.html', this);</script>
</div>
"this" points to the window object.
I think of putting an id to the script element and doing something like this:
<div id=write>
<script id='test'>include('src.html', document.getElementById('test').parentNode);</script>
</div>
Now elem in "include" function will point to the div containing the script element. In this case you are still relying on id but not on the div's side
When the page is loaded, all scripts will be executed sequencially, as soon as they are parsed. Therefore, you just need to get the last script that is apparent in the DOM to get the currently executed script:
var script = document.scripts[document.scripts.length-1];
ajax(url, function successCallback(html) {
script.insertAdjacentHTML("afterend", html);
});
(Demo to test - notice that document.scripts needs FF 9+)
However, I see no reason not to use serverside include().
nnnnnn was on the money, but I modified it ever so softly. I ended up making an include tag with a src attribute. On pageload I loop through all the "include" tags and fill them with the data from their src attribute:
function include(src, elem){
ajax.open('GET', src, false);
ajax.send(null);
elem.innerHTML = ajax.responseText;
}
window.onload = function(){
var includes = document.getElementsByTagName('include');
for(var i = 0; i <= includes.length; i++){
var elem = includes[i];
var src = elem.getAttribute('src');
include(src, elem);
}
}
Then anywhere I want to include a html file I just include my custom element:
<include src='includeme.html'> </include>
In practice this produces a bit of popup but for my application that's fine.
Thanks for the help!
I have a template file that is called myWebsite.html. It contains everything that HTML template needs to have. So it has HTML, HEAD and BODY tags. I want to load it with JavaScript and put into one of divs on the site. So i don't want to have the HTML, HEAD and BODY tags. How to do this?
This is a prototype of what i need to have:
$val = getData('myWebsite.html');
$val = removeHTMLHEADBODYTAGS($val); //remove these tags with everything insite, also remove the body tag but leave the contents in the body tag. Also remove the end tags of body and html - HOW TO DO THIS?
div.innerHTML = $val;
I want to do this in pure JavaScript = NO jQUERY
Why not fetch the information out of the tag and then work with that? There is no need to fetch all information and the removing html, head and body:
content = $val.getElementsByTagName('body')[0].innerHTML();
You could extract it with a regex. Something like: /\<body[^>]*\>(.*)\<\/body/m - that should return all content within the <BODY> element.
$val = getData('myWebsite.html');
var reg = /\<body[^>]*\>([^]*)\<\/body/m;
div.innerHTML = $val.match( reg )[1];
Example jsFiddle code: http://jsfiddle.net/x4hPZ/1/
With jQuery you could do it like this:
$(document).ready(function(){
var your_content = $("html").clone().find("head,body").remove().end().html();
});
get the content with "html" selector
make a copy with clone
find the tags you want to remove
remove them and
convert back to HTML
all in one line.
HTH,
--hennson
how about:
var bodyContents = htmlstring.split('<body');//no >, body could have a property
bodyContents = bodyContents[1].replace('</body>','').replace('</html>','').replace(/^.*\>/,'');
The last regex replace removes the closing > of the opening body tag, and all possible tag properties.
This is, however, not the way I would do things... If at all possible, I'd create an (i)Frame node, load the html into that frame, and get the innerHTML from the body tag. Just a suggestion.
Right, the iFrame way:
var document.ifrm = document.createElement('iframe')
document.ifrm.style = 'visibility:hidden';
document.body.appendChild(document.ifrm);
idoc = (document.ifrm.contentDocument ? document.ifrm.contentDocument : document.ifrm.contentWindow.document;)
idoc.open();
idoc.writeln('<html><head><title>foobar</title></head><body><p>Content</p></body></html>');
idoc.close();
var bodyContents = idoc.body.innerHTML;
For code explanation: http://softwareas.com/injecting-html-into-an-iframe
or any other hit on google.com for that matter :)
I have a text that represents some page. I need to convert this text to dom object, extract body element and append it to my dom.
I have used following code to convert text and extract body element:
$('body', $(text)).length
and:
$(text).filter('body').length
In both cases it returns 0...
To test: http://jsfiddle.net/wEyvr/1/
jQuery is parsing whole HTML in a non-standard way, so $(html) doesn't work as expected.
You can extract the content of the body tag using regexp and work from there:
// get the content of the body tags
var body = $(text.match(/<body[\s\S]*?>([\s\S]*?)<\/body>/i)[1]);
// append the content to our DOM
body.appendTo('body');
// bonus - to be able to fully use find -> we need to add single parent
var findBody = $("<body />").html(body.clone());
// now we are able to use selectors and have fun
findBody.find("div.cls").appendTo('body');
HERE is the working code.
EDIT: Changed the code to show both direct append and also using selectors.
Something like this:
var ifr = $("<iframe>"),
doc = ifr.appendTo("body")[0].contentWindow.document,
bodyLength;
doc.open();
doc.write(text);
doc.close();
bodyLength = ifr.contents().find("body").length;
ifr.remove();
alert(bodyLength);
http://jsfiddle.net/wEyvr/2/
i'm having some trouble with javascript. Somehow i can't get started (or saying i'm not getting any results) with html elements creation by javascript.
i'm not allowed to use:
document.writeln("<h1>...</h1>");
i've tried this:
document.getElementsByTagName('body').appendChild('h1');
document.getElementsByTagName('h1').innerHTML = 'teeeekst';
and this:
var element = document.createElement('h1');
element.appendChild(document.createTextNode('text'));
but my browser isn't showing any text. When i put an alert in this code block, it does show. So i know the code is being reached.
for this school assignment i need to set the entire html, which normally goes into the body, by javascript.
any small working code sample to set a h1 or a div?
my complete code:
<html>
<head>
<title>A boring website</title>
<link rel="stylesheet" type="text/css" href="createDom.css">
<script type="text/javascript">
var element = document.createElement('h1');
element.innerHTML = "Since when?";
document.body.appendChild(element);
</script>
</head>
<body>
</body>
</html>
getElementsByTagName returns a NodeList (which is like an array of elements), not an element. You need to iterate over it, or at least pick an item from it, and access the properties of the elements inside it. (The body element is more easily referenced as document.body though.)
appendChild expects an Node, not a string.
var h1 = document.createElement('h1');
var content = document.createTextNode('text');
h1.appendChild(content);
document.body.appendChild(h1);
You also have to make sure that the code does not run before the body exists as it does in your edited question.
The simplest way to do this is to wrap it in a function that runs onload.
window.onload = function () {
var h1 = document.createElement('h1');
var content = document.createTextNode('text');
h1.appendChild(content);
document.body.appendChild(h1);
}
… but it is generally a better idea to use a library that abstracts the various robust event handling systems in browsers.
Did you append the element to document?
Much the same way you're appending text nodes to the newly created element, you must also append the element to a target element of the DOM.
So for example, if you want to append the new element to a <div id="target"> somewhere are the page, you must first get the element as target and then append.
//where you want the new element to do
var target = document.getElementById('target');
// create the new element
var element = document.createElement('h1');
element.appendChild(document.createTextNode('text'));
// append
target.appendChild(element);
create element, add html content and append to body
var element = document.createElement('h1');
element.innerHTML = 'teeeekst';
document.body.appendChild(element);
I was wondering if there's a way in javascript that allows me to process the html source code that allows me to take out specific tags that I want?
Sorry if it sounds easy or too simple. i am new to programming.
If you have the HTML in a string, then you can use:
var str = '<html></html>'; // your html text goes here
var div = document.createElement('div');
div.innerHTML = str;
var dom = div.firstChild; // dom is the object you want,
// you can manipulate it using standard dom methods
Alternately, use jQuery. jQuery is a library to help you manipulate and access HTML elements more easily. First, add this to the head of your document:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
This is a reference to the jQuery library. Then, do:
var foo = $("<html>Your html here</html>");
Or, if your html is in a variable (e.g. str), you can do:
var foo = $(str);
Then, you can manipulate and parse foo in a number of ways. For example, to remove all paragraph elements, you would use
foo.remove('p');
Or, to remove the paragraph element with id="bar", use:
foo.remove('p.bar');
Once you are done your modifications, you can get the new html text using:
foo.html();
Why is your html in a string? Is it not the html of the current page?
Use DOM it can pull data from webpages if you know the structure.