How to add response body to Html [duplicate] - javascript

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.

Related

Creating a div within an existing div in javascript issues

I have a problem, I wanted to create a div in html as a container and in javascript create new divs within the container based on a number input from a user prompt.
My html and javascript look like this.
HTML:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<title>Sketchpad</title>
</head>
<body>
<button type="button">Reset</button>
<div class= "container">
</div>
<script src="javascript.js"></script>
<script src="jQuery.js"></script>
</body>
JS
var row = prompt("Enter number of rows:");
var column = prompt("Enter number of columns:");
function createGrid(){
var cont = document.getElementsByClassName('container');
for(i=1; i<column; i++){
var sketchSquare = document.createElement('div');
cont.appendChild(sketchSquare);
}
}
createGrid(column);
I end up with this error: Uncaught TypeError: cont.appendChild is not a function.
I imagine this is something to do with the getElementsByClassName?
I do have a solution which involves creating the container div in javascript and appending the smaller squares inside the container div. I was just curious as to why my first soltuion didn't work?
cont[0].appendChild(myDiv) is a function.
When you document.getElements By Class Name as the name implies you are getting many elements (an array of sorts) of elements and this array don't have the same functions as each of its elements.
Like this:
var thinkers = [
{think: function(){console.log('thinking');}
];
thinkers don't have the method .think
but thinkers[0].think() will work.
try this: open your javascript console by right clicking and doing inspect element:
then type:
var blah = document.getElementsByClassName('show-votes');
blah[0].appendChild(document.createElement('div'));
It works!
also if you want to use jQuery which I do see you added...
you can do:
var cont = $('container');
cont.append('<div class="sketchSquare"></div>');
Try that out by doing this:
First get an environment that has jQuery.
Hmm maybe the jQuery docs have jQuery loaded!
They do: http://api.jquery.com/append/.
Open the console there and at the bottom where the console cursor is type:
$('.signature').append('<div style="background: pink; width: 300px; height: 300px"></div>');
You'll notice that you add pink boxes of about 300px^2 to 2 boxes each of which have the "signature" class.
By the way, prompt gives you a string so you'll have to do row = Number(row); or row = parseInt(row, 10); and another thing don't use that global i do for(var i = 0; ...
var cont = document.getElementsByClassName('container');
Because that^ doesn't return a node, it'll return an HTMLCollection.
https://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html#htmlcollection-0
You need to pick an individual node from that collection before appending.
There could be a couple of issues that could cause this. Without fully giving the answer here's what it could be at a high level.
Your script is ran before the DOM is fully loaded. Make sure that your script is ran after the DOM is present in the page. This can be accomplished using either the DOMReady event ($(document).ready equivalent without jQuery) or simply making sure your script tag is the last element before the closing body tag. (I usually prefer the former)
When you utilize document.getElementsByClassName('container') (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) this method returns an array therefore you would either need to apply the operation to all elements of the result or just select the zero-th as document.getElementsByClassName('container')[0]. As an alternative, if you would like to be more explicit you could also place an id on the container element instead to more explicitly state which element you would like to retrieve. Then, you would simply use document.getElementById([id]) (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) and this would get back a single element not a collection.
The result of prompt is a string. Therefore you would have to first parse it as an integer with parseInt(result, 10) where 10 is simply the radix or more simply you want a number that is from 0-10.
You should include jquery library before your script, it`s important
<script src="jQuery.js"></script>
<script src="javascript.js"></script>

Getting value from a Input Box , Javascript, getElementById

SO i am trying to get the value or the contents of an HTML text box. I have tried various types of methods but none of them work. According to the debugger , the code stops at getelementbyid method. The commented lines are the methods that I have already tried. Some of them return null while some of them return NaN and most of them just return a blank page.
help is much appreciated.
<html>
<head>
<script type="text/javascript" >
function calculateit(){
document.open();
var number = document.getElementsByName('xyz')[0].value
//var number = document.getElementsByName("xyz").value;
//var number = document.getElementsByName('xyz').value;
//var number = document.getElementsByName("xyz");
//var number = document.getElementsByName('xyz');
//var number = document.getElementsById("xyz").value;
//var number = document.getElementsById('xyz').value;
//var number = document.getElementsById("xyz");
//var number = document.getElementsById('xyz');
//var number = document.form1.xyz.value; //form 1 was my form name and/or id
document.writeln(number);
var newtemp = 0;
var newtemp = tempera *9/5+32;
document.write(newtemp);
}
</script>
</head>
<body>
<input type="text" id="xyz" name="xyz">
<button title="calculate" onclick="calculateit()">calculate </button>
</body>
</html>
You're using the wrong method. The two widely supported methods for javascript are "getElementsByTagName" and "getElementById". Note exactly how "getElementById" is spelled. It is meant to get one element with the exact id that you specify. "getElementsByTagName" gets all elements of a certain tag...such as "div". When using "getElementById", you don't to index it or anything - it either returns null (can't find) or the exact element reference. From there, since it is a textarea, you can use ".value" to get the current value, like you already are.
ALSO:
You probably shouldn't use "document.write" or any of its related write methods AFTER the page has been rendered. In your example, that's exactly what you're doing, so once you get the ".value" stuff working, I would change that. The point is that "document.write" is more for during page rendering...so if you had javascript inline with the HTML body or something. Something like:
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("testing");
</script>
</body>
</html>
would be fine, but still not preferred. The fact that you have it in a function, that is called on a button click, means it is not during page render, and shouldn't be used. A more practical approach is to have a <div> on the page and add text to it when necessary, using something like ".innerHTML". That way, things are dynamic and not overwritten in the actual document.
It's getElementById, not getElementsById.

Filter out HTML Tag onpaste for div and oncopy too

I have an editable DIV in my site to send a forum message. People can edit their messages (Bold, Italic, underline, add links and more)
But I want when some one paste or drop (- drop is not necessary, but paste it is) their text I want it to go in the DIV without HTML tags - clean, just text. (like if some one is going to word and make the text 200 points size, then copy & paste it in my DIV, they will have a very different message... and I don't want it to happen).
How can I scan the text coming from the clipboard to remove any HTML tags and then paste it in the DIV?
<html>
<head>
<script type="text/javascript" language="javascript">
function PasteFilter()
{
//windows.clipboardData filter on paste to go here
}
function CopyFilter()
{
//windows.clipboardData filter on copy to go here
}
</script>
</head>
<body>
<Div class="body" onpaste="PasteFilter()" oncopy="CopyFilter">
<!-- div content goes here.-->
</Div>
</body>
</html>
I would like to also apply the same filter with COPY too.
Thanks
I believe there are 2 ways to do this:
1) The easy way - insert the following code in PasteFilter():
var foo = window.clipboardData.getData('Text');
window.clipboardData.setData('Text', foo);
the first line gets the Text value of clipboardData (already stripped of HTML tags)
and the second line sets the clipboardData to the plain text...
(Tested on IE8)
2) The other way - if for some reason that isn't suitable for you..
In PasteFilter(), you trigger another function with a small delay timeout.
In that function, you get the innerHTML contents of the DIV and run a regular expression to remove all tags.
Example:
function PasteFilter()
{
setTimeout('foo()', 200);
}
function foo()
{
var contents = document.getElementById("test").innerHTML;
var new_contents = contents.replace(/(<([^>]+)>)/g, ""); // taken from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
document.getElementById("test").innerHTML = new_contents;
}
The problem with this method is that you lose the caret position...
Hope this helps...

IE9, Javascript: Create and append a new 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>

dynamically insert javascript into <head> tag

I am using CEWP (webpart) and putting this code in there. But this code is not going inside <head> tag. I need to insert this code in <head> tag,
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$("*").each(function () { if ($(this).children().length == 0) { $(this).text($(this).text().replace('Respuesta','Responder')); } });
</script>
How can I do this? How this code will work in CEWP webpart?
Firstly, you can put the code in the <head> if you set it to run at document ready time.
However, it's still not going to work. You're iterating over all tags. Including <html>, which will be the first one selected by $('*').
So you read all the text inside the <html> element (ie. the entire document text), do a string replace on it, then write it back to the html text(). Replacing all the previous text and element content of the <html> element with a single simple text string. And thereby destroying every other element on the page. Oops.
What you want to do is find every text node and do a separate string replace on it:
$(document).ready(function() {
$('*').each(function() {
for (var i= this.childNodes.length; i-->0;) {
var child= this.childNodes[i];
if (child.nodeType===3) // TEXT_NODE
child.data= child.data.replace(/Respuesta/g, 'Responder');
}
});
});
(Note there are still a bunch of possible edge cases here with form fields and other elements where changing the text inside them might not do what you expect.)

Categories