How to display Javascript Variable value to HTML Document - javascript

If I use document.write() it clears the whole html document. So how can I take this javascript variable
var beforenoonprice = 6.75;
and have it display to the html document through this div
<div id="beforeNoonCPSlot"></div>

You use the DOM API:
document.getElementById("beforeNoonCPSlot").innerHTML = String(beforenoonprice);
List of DOM API specs.
(In the above, I've explicitly converted the price to a string, but that's just for emphasis; if I hadn't, there would have been an implicit conversion.)
Note that you have to execute that line of code after the element has been created, otherwise we can't find it with document.getElementById. Given that you've said that using document.writeln cleared the whole document, it sounds like you're running your code at a point where the document as a whole has been rendered, so that should be fine.

Related

Remove JavaScript code from page with JavaScript

I have a chunk of JavaScript code:
<script src='blah.js' type='text/javascript'></script>
How can this be removed or disabled with JavaScript?
If the script tag is received in a string via AJAX:
str = str.replace("<script src='blah.js' type='text/javascript'></script>", "");
However, if the script tag is in the current document, there is no way to disable it, because:
If it is in the part of the document which has already been parsed (i.e. above the current script), it has already been executed. While you can remove the script element, just like any element, there is no way to rewind time and automatically undo the effects the script has.
If it is in the part of the document which has not yet been parsed (i.e. below the current script), you cannot affect it, as it does not exist yet.
You can grab the script like any other element, you can do this:
document.querySelector("script").remove();
If you have a lot of script tags you can just grab the one you want like accessing a array element like so:
document.querySelectorAll("script")[1].remove();
The code above removes the second script tag in a page.

How to insert created object into a div

I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]"
What could be the reason for this?
Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/2/
You want to use the appendChild method rather than innerHTML. Change the last line in the JSFiddle from
iframediv.innerHTML = iframe;
to
iframediv.appendChild(iframe);
Edit to actually answer your question:
Your variable iframe is a reference to a DOM element. It's object representation is an <iframe> element while its textual representation is simply [object HTMLIFrameElement].
By using innerHTML you are attempting to insert its textual representation into the DOM. This is just how the method works. You may come across JS code where elements are added to the DOM via innerHTML, but it's always with text, e.g.
element.innerHTML = '<div>some text</div>';
In this case the browser will correctly add a <div> node as a child of element.
For your <iframe> element to be inserted into the DOM using the variable iframe, you must use the appendChild method which will add the IFrame object as a child node to iframediv.
$('#iframecontainer').append(iframe);
instead of
var iframediv = document.getElementById('iframecontainer');
iframediv.innerHTML = iframe;
should fix the problem
var new_iframe = $("<iframe></iframe>");
new_iframe.appendTo($("#div_to_insert_into"));
The idea behind (most) of the posted solutions is that you can work with your iframe and it's container as jQuery objects instead of regular dom elements. A jQuery object is a reference to a div or an iframe that has access to all of jQuery's awesome methods... like .append() and .click().
Generally speaking, jQuery's real purpose is to turn lines of code like
var iframediv = document.getElementById('iframecontainer');
...into ...
var iframediv = $("#iframecontainer");
...which you can then use to do with whatever you please, like
iframediv.appendTo("#anotherDiv");
Good luck.

Access $('selector').data in functions/objects

How do I access values set by $.data() inside a function or object
$('#timers').data('firsttimer', 100);
//prints 100
document.write($('#timers').data('firsttimer'));
function blah(){
//Prints nothing
document.write($('#timers').data('firsttimer'));
}
blah();
See this jsfiddle for easy access to test the code http://jsfiddle.net/JUfd8/
I'm having trouble with document.write() inside the function call for some reason, but it works fine if I use jQuery's .append().
function blah(){
$('body').append($('#timers').data('firsttimer'));
};
EDIT:
Found this stackoverflow question regarding document.write:
Why is document.write considered a "bad practice"?
An interesting sentence from one of the answers in that post:
As long as you don't try to use it after the document has loaded, document.write is not inherently evil, in my humble opinion.
So that may be the key to the trouble (or part of it, anyway).
The trouble is in "document.write()". Try to avoid it.
In this case, I believe your document.write is stomping on the DOM in some strange way, wiping out your timers div. Switching both of the document.write calls to alert calls instead (and adding a line to invoke blah()) allowed me to see both alert boxes, both showing the value 100.
<div id="timers"></div>
js code:
$('#timers').data('firsttimer', 100);
//shows 100
alert($('#timers').data('firsttimer'));
function blah(){
//Prints nothing
alert($('#timers').data('firsttimer'));
}
blah();
The behavior is not consistent across all browsers. Remember, on jsfiddle this code is already wrapped inside the window load callback since you chose the onLoad setting on the left. Once the DOM is loaded, any subsequent changes using document.write will replace the entire document.
Here's the relevant text from the HTML5 specs on document.write:
Unless called from the body of a script element while the document is being parsed, or called on a script-created document, calling this method will clear the current page first, as if document.open() had been called.
Here's how the browsers are behaving on my Mac given this code:
Chrome and Safari
Wipes out the document altogether. Even 100 isn't printed. Text nodes by themselves are being ignored here, but when wrapped inside some html tag - they show up. This code is the same as above with the values wrapped inside <b> and <i> tags respectively.
Opera and Firefox
Wipes out the document, then appends the text node "100undefined". It prints "undefined" because the node <div id="timers></div> does not exist anymore in the new document.
However, it does print "100" the first time you call document.write on Opera and Firefox
document.write($('#timers').data('firsttimer'));
because the function argument $('#timers').data('firsttimer') is evaluated first and since the original document is intact at this point, we get the value 100, which is then passed to document.write, that then recreates the entire document. Therefore, all subsequent calls to fetch the data associated with #timers returns undefined.

Does jQuery strip some html elements from a string when using .html()?

I have a var that contains a full html page, including the head, html, body, etc. When I pass that string into the .html() function, jQuery strips out all those elements, such as body, html, head, etc, which I don't want.
My data var contains:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
Then my jQuery is:
// data is a full html document string
data = $('<div/>').html(data);
// jQuery stips my document string!
alert(data.find('head').html());
I am needing to manipulate a full html page string, so that I can return what is in the element. I would like to do this with jQuery, but it seems all of the methods, append(), prepend() and html() all try to convert the string to dom elements, which remove all the other parts of a full html page.
Is there another way that I could do this? I would be fine using another method. My final goal is to find certain elements inside my string, so I figured jQuery would be best, since I am so used to it. But, if it is going to trim and remove parts of my string, I am going to have to look for another method.
Ideas?
After a few quick tests it seems do me that this behavior isn't caused by jQuery but instead by the browser.
As you can easily verify yourself (DEMO http://jsbin.com/ocupa3)
var data = "<html><head><title>Untitled Document</title></head><body><p>test</p></body></html>";
data = $('<div/>').html(data);
alert(data.html());
yields different results in different browsers
Opera 10.10
<HEAD><TITLE>Untitled Document</TITLE></HEAD><P>test</P>
FF 3.6
<title>Untitled Document</title><p>test</p>
IE6
<P>test</P>
so this has nothing to do with jQuery, It's the browsers which strip some tags when you insert a whole html string inside a div. But you would need to step through the whole jQuery code for html() to be sure. And you would need to do that for all browsers as there are several different ways jQuery tries to do it's job.
For a solution I advise you to investigate using an iframe (possibly hidden) and to set that iframe content to the html-string you have. But be aware that fiddling with iframes and changing their content programmatically isn't an easy task either. There are also different browser related quirks and timing issues involved.
Here is a solution, which will include the body, head and other attributes:
mydoc = document.getElementById('NAME_OF_PREVIEW_FRAME').contentWindow.document; mydoc.write(HTML_CODE); mydoc.close();
Nope, the jQuery html function is just sending the string through to the element's innerHTML property, which is a function of the browser that tells it to parse the HTML into DOM elements and add them to the page.
Your browser doesn't work with a page as HTML data, it works with it as DOM and imports/exports HTML.
JavaScript has very good Regular Expression support. Depending on the complexity of your task, you may find this is the best way to process your data.
There is no need for the container div.
Have you tried this?:
var foo = $(data); // data is your full html document string
Then you can search inside of it like so:
$('.someClass', foo); // foo is the document you created earlier
Update:
As another answered mentioned, how this will act comes down to the browser.
I looked at the jQuery docs a bit and found this:
When the HTML is more complex than a
single tag without attributes, as it
is in the above example, the actual
creation of the elements is handled by
the browser's innerHTML mechanism.
Specifically, jQuery creates a new
<div> element and sets the innerHTML
property of the element to the HTML
snippet that was passed in.
So it seems that when you are using a whole html doc as a string, it's no different than setting the innerHTML property of a div you make using createElement.

How to read all child elements with tag names and their value from a xml file?

I've a xml file in which I'm storing some HTML content in an element tag called <body>. Now I'm trying to read all the HTML content of body tag using XML DOM in JavaScript.
I tried this code:
var xmlDoc=loadXMLDoc('QID_627.xml');
var bodytag = xmlDoc.getElementsByTagName("body");
document.write(bodytag);
but it is showing [object HTMLCollection] message on the browser screen.
Try this:
var xmlDoc=loadXMLDoc('QID_627.xml');
var bodytags = xmlDoc.getElementsByTagName("body");
document.write(bodytags[0]);
getElementsByTagName returns an array of elements (even if just one is found) so you need to subscript the array to retrieve your element.
Andrew Hare pointed out that getElementsByTagName() always returns an array, so you have to use bodytag[0] to get the element you want. This is correct, but not complete since even when you do that you'll still get an equally useless "[object ElementName]" message.
If you're set on using document.write() you can try to serialize out the content of the body tag with
document.write(bodytag[0].innerHTML);
Better yet would be directly attaching the source DOM nodes into your destination DOM.
You'd use something like
document.getElementById("destinationNodeId").appendChild(bodytag[0]);
There may be some issues with attaching DOM nodes from another document that may require you to copy the nodes, or jump through some other hoops to have it work.
You need to use document.write(bodytag.toXMLString());
EDIT: Andrew Hare also points out you need to subscript first. I think you may still need to use the toXMLString call as well.

Categories

Resources