currently i am using bellow code
<html>
<head>
<script>
window.onload = function(){
var parser = new DOMParser();
var html = "<html><body><p>this is" +
"<script>document.write('dynamic')<\/script> text.</p></body></html>";
var doc = parser.parseFromString(html,'text/html');
document.body.appendChild(doc.body.children[0]);
}
</script>
</head>
<body>
<p>this is <script>document.write('dynamic')</script> text.</p>
</body>
</html>
that shows : this is dynamic text.
but currently i am loading page dynamicaly by ajax
and parsing using new DOMParser.
but it not prints "dynamic" only shows: this is text.
You can use the DOM manipulation methods shown here:
var h = document.createElement("H1") // Create a <h1> element
var t = document.createTextNode("Hello World"); // Create a text node
h.appendChild(t);
or here: document.getElementById("demo").innerHTML = "Paragraph changed!";
As you are currently loading the page via AJAX, you probably have to make sure that everything flows in the right order, i.e.: the change of the DOM is done after the page is received, etc. (Don't know your surrounding code, so I can't really speak to that).
Related
This should be a pretty easy thing to do, but it's not returning anything.
The function love() should kick off, getting a simple number prompt, and spitting out a list of a few items that uses that starting number.
the alert box correctly displays what I expect, but I want it to display on the screen.
(this is but a small section of what I'm after, but it's the kernel of it). No text is displaying in the IE, FF, or Chrome...
<script type="text/javascript">
function love()
{
var ncxElement="";
var idNumber = prompt("Enter beginning number","");
var myText=document.getElementById("here");
for (var i=1;i<5;i++)
{
ncxElement+=("<navPoint class=\"other\" id=\"page_"+idNumber+"\">\n");
idNumber++;
}
alert(ncxElement);
myText.innerHTML=ncxElement;
}
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>
If you want to display HTML on your page (without it being parsed), use .textContent instead of .innerHTML and wrap it in a <pre> (to preserve the line breaks).
Demo:
Change:
myText.innerHTML=ncxElement;
To:
myText.textContent=ncxElement;
Change:
<p id="here">Begin!</p>
To:
<pre id="here">Begin!</pre>
navPoints are not valid html elements, so the browser doesn't know what to do with them. They are being added to the DOM, just not displayed unless you add styling to do so.
If you replace them with paragraph tags, it works fine. See the example here.
<script type="text/javascript">
function love()
{
var ncxElement="";
var idNumber = prompt("Enter beginning number","");
var myText=document.getElementById("here");
for (var i=1;i<5;i++)
{
ncxElement+=("<p class=\"other\" id=\"page_"+idNumber+"\">"+idNumber+ "</p>");
idNumber++;
}
alert(ncxElement);
myText.innerHTML=ncxElement;
}
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>
Your function just wraps elements inside another. There is no text inside or outside these elements to dipslay.
Try inserting some random text before closing tags to see the result.
Btw, the elements are successfully placed in the p tag.
I have an app that uses HTML Email templates. I want to write a script that parses through the HTML of an email template and modifies the code. This is easy when the template is loaded on the page, but I want to do these dynamically where the HTML is just a value from a <textarea> (or more specifically CodeMirror).
The value of the <textarea> (CodeMirror) would look like this:
<!doctype html>
<html>
<head>...HEAD HTML...</head>
<body>...BODY HTML...</body>
</html>
I've tried:
// This part works great. Stores the HTML as a varaible.
var template_html = codeMirrorInstance.getValue();
// This shows the proper HTML in console as text
console.log(template_html);
// From here I can't access the HTML though
console.log($(template_html).find('body'));
But I keep getting undefined. Nothing I try is working... any ideas?
It appears you can do what you are trying to do. You just have to create a new document and possibly an second instance of jQuery.
You should take a look at this: https://stackoverflow.com/a/15496537/1819684 and this: https://stackoverflow.com/a/15479402/1819684
$(function() {
var doctype = document.implementation.createDocumentType( 'html', '', '');
var dom = document.implementation.createDocument('', 'html', doctype);
var jq2 = jQuery(dom);
var txt = $('textarea').val();
console.log(jq2.find('html').html(txt).find('body'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<html>
<head>...HEAD HTML...</head>
<body>...BODY HTML...</body>
</html>
</textarea>
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'm having some serious trouble getting my code to work in IE9, works fine in Chrome & Firefox but I throws some errors. Here are my 2 functions:
function insertHTML(content){
var body=document.getElementsByTagName('body');
body[0].appendChild(createElement(content));
}
function createElement(string){
var container=document.createElement('div');
container.innerHTML=string;
var element=container.firstChild.cloneNode(true);
return element;
}
I've tried severel methods for this and none seem to work, I'll explain exactly what I need to do...
...I need to create a new element from an html string, the string is sent back from an ajax call so my script will have almost no idea what it contains until it gets it.
I did try using element.innerHTML but this is no good, because if i have one html element (form) on the screen and the user enters data into it, and then when another element is inserted it will wipe all the user-entered data from the first form. I was doing element.innerHTML+=newData;
So basically, I need 2 things:
1) A way to create a new element from an html string.
2) A way to append the element to the document body.
It all needs to work cross-browser and I'm not allowed to use jQuery, also the new element cannot be contained in a div parent item, it has to have the body as its parent.
Thanks very much for your help,
Richard
innerHTML is read write and will destroy anything inside your div. use with extreme care
function insertHTML( htmlString ){
var bodEle = document.getElementsByTagName('body');
var divEle = createElement("div");
divEle.innerHTML = htmlString;
bodEle.appendChild(divEle);
}
So basically, I need 2 things:
A way to create a new element from an html string.
A way to append the element to the document body.
It all needs to work cross-browser and I'm not allowed to use jQuery, also the new element cannot be contained in a div parent item, it has to have the body as its parent.
The following was tested in IE8
<!DOCTYPE html>
<html>
<body>
<script>
var divBefore = document.createElement('div');
var divAfter = document.createElement('div');
var htmlBefore = '<span><span style="font-weight: bold">This bold text</span> was added before</span>';
var htmlAfter = '<span><span style="font-weight: bold">This bold text</span> was added after</span>';
divBefore.innerHTML = htmlBefore;
divAfter.innerHTML = htmlAfter;
document.body.appendChild(divBefore);
setTimeout(function() {
document.body.appendChild(divAfter);
}, 0);
</script>
<div>This content was here first</div>
</body>
</html>
Renders
This bold text was added before
This content was here first
This bold text was added after
https://www.browserstack.com/screenshots/7e166dc72b636d3dffdd3739a19ff8956e9cea96
In the above example, if you don't need to be able to prepend to the body (i.e. insert content before what already exists), then simply place the script tag after the original content and don't use setTimeout.
<!DOCTYPE html>
<html>
<body>
<div>This content was here first</div>
<script>
var divAfter = document.createElement('div');
var htmlAfter = '<span><span style="font-weight: bold">This bold text</span> was added after</span>';
divAfter.innerHTML = htmlAfter;
document.body.appendChild(divAfter);
</script>
</body>
</html>
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);