Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically add a paragraph to a document without overwriting everything else in javascript?

I'm just learning how to write javascript, but i've already learned java. the difference in syntax is driving me nuts. i'm just doing a dumb little sample code to see if i can add a paragraph to the end of a page at the click of a button. but i can't seem to do it. i'm positive that i'm really close to achieving my goal though. i already know the button functions properly. there is a similar post that has helped me, but i can't seem to quite get to where i want. here's the javascript:

function displayDate()
{
//object that will hold newParagraph
var iframe = document.createElement("iframe");
iframe.width = 400;
iframe.height += 50;
iframe.id ="iframe";

var comment = "woohooo! go me.";
//var doc = iframe.contentDocument || iframe.document;
var newParagraph = document.createElement('p');
newParagraph.textContent = comment;

//doc.body.appendChild(newParagraph);
iframe.appendChild(newParagraph);
document.getElementById("updateDiv").appendChild(iframe);
//the id updateDiv is in my html
}

the iframe shows up as a blank box without the text. i cannot figure out how to get the text to appear in the iframe.

here's the similar post if you're curious: Adding iframe and paragraph elements dynamically

like image 202
luke Avatar asked Oct 20 '25 05:10

luke


1 Answers

If you just want to add a paragraph to the document, ditch the iframe. An iframe embeds a completely new document inside your browser window. For your purposes, simply appending the <p> element onto the <div id='updateDiv'> should be enough:

function displayDate() {
    var comment = "woohooo! go me.";
    var newParagraph = document.createElement('p');
    newParagraph.textContent = comment;
    document.getElementById("updateDiv").appendChild(newParagraph);
}

and here's the HTML:

<button id='a'>Click Me!</button>
<div id='updateDiv'></div>    

And here's the fiddle example: http://jsfiddle.net/MYy72/

like image 151
devoid Avatar answered Oct 21 '25 20:10

devoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!