Place content in JavaScript (HTML files) - javascript

How to place content (example: simple text) in JavaScript?
I need it to be like youtube, where the video is only visible on JavaScript enabled browser.
Thanks.

Using the noscript tag, like this:
<script type="text/javascript">
document.write("Hello World!")
</script>
<noscript>
Your browser does not support JavaScript!
</noscript>
You might also want to consider putting the script in some sort of HTML comment so that browsers that don't even know about script don't render the source code, e.g.:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>

You need to append a new DOM node to the DOM (Document Object Model).
The simplest one would be this:
var myNewNode = document.createTextNode('abc');
As for all more advanced nodes, you can create them as follows:
var myNewNode = document.createElement('div');
myNewNode.className = 'cssClass';
myNewNode.innerHTML = 'abc';
Something that's a little neater than setting "innerHTML", however, especially if you're adding complex content, and want to hook up events to it etc, is to add children to that node:
var myNewNode = document.createElement('div');
var myChildNode = document.createElement('input');
myChildNode.type = 'button';
myChildNode.value = 'Click me';
myNewNode.appendChild(myChildNode);
Assuming, then, that you've created myNewNode in any of the ways described above, you just need to locate the place in your document where you want to add the new node, and insert it:
document.body.appendChild(myNewNode);
or
document.getElementById('container').appendChild(myNewNode);

Related

Add contents to a new empty iframe

I have a new iframe. It takes src and includes a completely empty page. Now I want to fill it with data trough javascript.
In normal cases I can do this:
var content = "Some content";
$("iframe").contents().find("body").html(content);
But this iframe is empty and has no body or html. Is it possible to include content to it anyway?
Something like this should be inserted:
<html>
<head></head>
<body>Hello</body>
</html>
Update
I can do this:
$('iframe').contents().find('html').html('<html><body>test</body></html>');
I don't know if it will render double html tags or not. In the developer tool I can't see that it add an extra.
You can get hold of the IFrame window by a normal query selector.
var myFrameDoc = document.getElementById('iframe_id').contentDocument;
If it has nothing, write it.
myFrameDoc.write('<html>');
myFrameDoc.write('<head>');
myFrameDoc.write('</head>');
myFrameDoc.write('<body>');
myFrameDoc.write('<div>Hello iFrame</div>');
myFrameDoc.write('</body>');
myFrameDoc.write('</html>');
There are more ways you can do this. I will leave it for you to realize.
In jQuery it seems to be no solution. Instead I needed to do it like this:
var content = '<html><head></head><body>Hello</body></html>';
var iframe = document.getElementById( '#iframe_id' );
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(content);

Find the tag JavaScript is running in

Generating HTML source on backend, I am using separate independent widgets.
I am simply including pieces of markup like this to the resulting HTML output.
<div>
I want to work with this DOM element
<script>
new Obj(/*but I can't get this <div> as a parameter! */);
</script>
</div>
I'm looking for a way to find the DOM element in which the obj is created (Without any unique IDs). This would add flexibility to my app and speed up the development. But is that technicaly possible in JavaScript?
You could seed an element in there and then get it's parent, and then remove the element.
<div>
I want to work with this DOM element
<script>
document.write("<div id='UniqueGUID_3477zZ7786_' style='display:none;'></div>");
var thatDivYouWanted;
(function(){
var target = document.getElementById("UniqueGUID_3477zZ7786_");
thatDivYouWanted = target.parentNode;
target.parentNode.removeChild(target);
})();
new Obj(/*but I can't get this <div> as a parameter! */);
</script>
</div>
The following code works:
<script>
function Obj(color) {
var scriptTags = document.getElementsByTagName("script");
var scriptTag = scriptTags[scriptTags.length - 1];
// find parent or do whatsoever
var divTag = scriptTag.parentNode;
divTag.style.backgroundColor = color;
}
</script>
<div>
I want to work with this DOM element
<script>new Obj("green");</script>
</div>
<div>
I want to work with this DOM element
<script>new Obj("yellow");</script>
</div>
<div>
I want to work with this DOM element
<script>new Obj("lime");</script>
</div>
This method has very simple code and has almost zero impact on performance.
Note: I am pretty sure this won't work IE6 (as far as I remember it does not support manipulating open tags).
I believe your approach is not ideal. If you're trying to obtain the <div>, it should be done programmatically in a conventional way using JavaScript and the API's that empower you to query the target <div>
Instead of executing inline, you can execute in a separate scope in a controlled way (DOM Ready then Query then Your Method). You can target your div by using an ID, CSS class name, or any other CSS selector in JavaScript.
This allows you to pretty much do the follow anywhere you want, not inline.
// on dom ready...
var div = document.getElementById('myDiv'), // replace with any other selector method
myObject = new Object(div);
Need to find your div? https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll
If you know beforehand how the page will be structured, you could use for example:
document.getElementsByTagName("div")[4]
to access the 5th div.

creating html by javascript DOM (realy basic question)

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);

document.write() and Ajax - Doesn't work, looking for an alternative

I recently asked a question here, and received a great response (which I will shortly be accepting the most active answer of, barring better alternatives arise) but unfortunately it seems the of the two options suggested, neither will be compatible with Ajax (or any dynamically added content that includes such "inline-relative jQuery")
Anyways, my question pertains to good ole' document.write().
While a page is still rendering, it works great; not so much when an appended snippet contains it. Are there any alternatives that won't destroy the existing page content, yet still append a string inline, as in where the call is occurring?
In other words, is there a way/alternative to document.write() that when called post-render, doesn't destroy existing page content? An Ajax friendly version so to speak?
This is where I'm going:
var _inline_relative_index = 0;
function $_inlineRelative(){
// i hate non-dedicated string concatenation operators
var inline_relative_id = ('_inline_relative_{index}').replace('{index}', (++_inline_relative_index).toString());
document.write(('<br id="{id}" />').replace('{id}', inline_relative_id));
return $(document.getElementById(inline_relative_id)).remove().prev('script');
}
And then:
<div>
<script type="text/javascript">
(function($script){
// the container <div> background is now red.
$script.parent().css({ 'background-color': '#f00' });
})($_inlineRelative());
</script>
</div>
you have access to the innerHTML property of each DOM node. If you set it straight out you might destroy elements, but if you append more HTML to it, it'll preserve the existing HTML.
document.body.innerHTML += '<div id="foo">bar baz</div>';
There are all sorts of nuances to the sledgehammer that is innerHTML, so I highly recommend using a library such as jQuery to normalize everything for you.
You can assign id to the script tag and replace it with the new node.
<p>Foo</p>
<script type="text/javascript" id="placeholder">
var newElement = document.createElement('div');
newElement.id='bar';
var oldElement = document.getElementById('placeholder');
oldElement.parentNode.replaceChild(newElement, oldElement);
</script>
<p>Baz</p>
And if you need to insert html from string, than you can do it like so:
var div = document.createElement('div');
div.innerHTML = '<div id="bar"></div>';
var placeholder = document.getElementById('placeholder'),
container = placeholder.parentNode,
elems = div.childNodes,
el;
while (el = elems[0]) {
div.removeChild(el);
container.insertBefore(el, placeholder);
}
container.removeChild(placeholder);

Extracting Metadata from Website

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.

Categories