Using getElementById to duplicate content in page - javascript

I don't know javascript and I have been searching every where for this answer. I would like to duplicate content in my page. The html and content comes directly from a broker.
The result wanted is :
Click the button to change the text in this paragraph.
Click the button to change the text in this paragraph.
My HTML is:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
var elem = document.getElementById('demo').setAttribute('id', 'nextstep');
document.write(elem);
</script>
</body>
</html>
What I am getting is:
Click the button to change the text in this paragraph.
undefined
Can somebody help point me in the right direction? Thanks in advance!

I don't believe you want to be using document.write. I think this is what you're after:
<script language="javascript" type="text/javascript">
// this gets the element
var elem = document.getElementById('demo');
// this copies the entire element, including the id
var newElem = elem.cloneNode(true);
// this sets a new id
newElem.setAttribute('id', 'nextstep');
// generic way to make sure you insert properly
var before = elem.nextSibling;
// there's no insertAfter, only insertBefore, which is why we found the before
elem.parentNode.insertBefore(newElem, before);
</script>
FIDDLE

You need to grab the innerHTML and set it:
var elem = document.getElementById('demo').innerHTML;
document.write(elem);
Beware though, document.write is going to overwrite everything..

If u need to get this
<p id="demo">Click the button to change the text in this paragraph.</p>
<p id="nextstep">Click the button to change the text in this paragraph.</p>
try
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
var elem = document.getElementById('demo');
var newElem = document.createElement('div');
newElem.innerHTML = "<p id='nextstep'>" + elem.innerHTML + "</p>";
document.write(newElem.innerHTML);
</script>
</body>
</html>

You are setting elem to the return value of setAttribute, which is undefined as it returns nothing.
Change the code to:
var elem = document.getElementById('demo');
elem.setAttribute('id', 'nextstep');
document.write(elem.innerHTML);
Example - http://jsfiddle.net/P8EcL/
This still does not end up with exactly what you want as it is copy of the content of the p tag rather than the tag itself.
Scott Mermelstein's answer is what you want.

var elem = document.getElementById('demo').innerHTML;
document.write(elem);
I'm not sure why you're trying to set a new id on the original div and expect it to return the HTML, but it's not going to work ;)

Related

button onclick function is not called

I'm making a webpage and when a button is clicked, it will delete every element inside the HTML element and append an iframe. Although, it doesn't seem to be working.
index.html:
<html id="html">
<head>
<script type="text/javascript" src="/freevpn/script.js"></script>
</head>
<body>
<input type="text" id="input" value="https://">
<button onclick="submit()">Go!</button>
</body>
</html>
script.js:
function submit() {
var submit = document.getElementById("submit");
var input = document.getElementById("input");
var iframe = document.createElement("iframe");
var html = document.getElementById("html");
iframe.setAttribute("src", input.value);
html.innerHTML = "";
html.appendChild(iframe);
iframe.requestFullscreen();
}
I'm not sure why this isn't working, but it has to be something. Thanks in advance!
NEW UPDATE: There were a few problems. It is linking to the javascript, I fixed the function, and I added parenthesis, but it doesn't seem to be updated in the browser. I've cleared my cache and everything, and it still isn't updating. My website is linked through Freenom, Cloudflare, Google Analytics and Search Console, so does it just take a while to update? And if so, is there a way to make it faster?
Try this, you are calling the function incorrectly.
You must use the () to call a function:
<button onclick="submit()">Go!</button>
function submit() {
var submit = document.getElementById("submit");
var input = document.getElementById("input");
var iframe = document.createElement("iframe");
var html = document.getElementById("html");
iframe.setAttribute("src", input.value);
html.innerHTML = "";
html.appendChild(iframe);
iframe.requestFullscreen();
}
<html id="html">
<head>
<script type="text/javascript" src="/freevpn/script.js"></script>
</head>
<body>
<input type="text" id="input" value="https://www.youtube.com/embed/_70Q-Xj3rEo">
<button onclick="submit()">Go!</button>
</body>
</html>
You are missing the parentheses when you are calling your JavaScript function. Try the below:
<button onclick="submit()">Go!</button>
Here is a handy reference for the onclick Event: https://www.w3schools.com/jsref/event_onclick.asp
Also it is a good idea to call put your <script> tag at the bottom of the body (i.e. below the button in your code snippet). This is because the Javascript file will be loaded first and the HTML elements may not have been created yet that you are accessing with the DOM.

Neither jQuery's .text() nor JavaScripts .innerText works?

I'm currently trying to animate some text on my website and set up a little test website to fiddle around with.
This is what my test website looks like:
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
//What I tried with jQuery
console.log("Content: " + $('p').text());
//What I tried with JavaScript
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
//This returns the HTMLCollection object, text[0] is undefined
var text = document.getElementsByClassName('test');
console.log(text);
</script>
</head>
<body>
<p class="test">Hello World!</p>
</body>
//What I tried with jQuery
console.log("Content: " + $('p').text());
//What I tried with JavaScript
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
//This returns the HTMLCollection object, text[0] is undefined
var text = document.getElementsByClassName('test');
console.log(text);
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<p class="test">Hello World!</p>
Here I'm already trying to use jQuery instead of JavaScript, because it seemed to be easier to use. But if I visit my website (locally) it only prints Content: inside the console (JavaScripts .innerText would return undefined).
If it is important: I'm using Ubuntu 19.10 to develop and test my website.
You need to wait for the page to load (DOM) before the script runs. As I see it now, your script runs before the paragraph (<p>) element is created.
You can either:
1) Make it so that the code runs once the page has loaded. (recommended) ... or
2) Move the script after the paragraph (<p>) tag.
Method 1
// jQuery
$(document).ready(function() {
console.log("Content: " + $('p').text());
});
// JavaScript
document.addEventListener("DOMContentLoaded", function(){
// Handler when the DOM is fully loaded
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
});
Method 2: Please refer to #Edit's answer.
Your script needs to be at the bottom of your body. Here's the result:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<p class="test">Hello World!</p>
<script>
//What I tried with jQuery
console.log("Content: " + $('p').text());
//What I tried with JavaScript
var text = document.getElementsByClassName('test').item(0);
console.log(text.innerText);
//This returns the HTMLCollection object, text[0] is undefined
var text = document.getElementsByClassName('test');
console.log(text);
</script>
</body>

Passing Javascript string var to HTML href tag

Due to limitations, I have to set a URL string on every page header in my website as a JavaScript string variable like this var burl = "http://www.example.com";
Now, I have to pass this string burl inside an HTML href="" tag in the of my website. I also want to be able to add extra URL elements to the href link beside the burl.
Here's what the full code look like Javascript + HTML code;
<script>
var burl = "http://www.example.com";
</script>
<html>
<head>
</head>
<body>
<h1>JavaScript Variables</h1>
<p>the href below should link to http://www.example.com</p>
Open Here
</body>
</html>
Any help solving this simple issue will be appreciated.
You can do that in two ways:
document.write
Via the DOM
document.write:
In a script tag where you want the link:
document.write('Open here');
That's processed during the parsing of the page, and replaces the script link with the text you output.
Live example:
<script>
var burl = "http://www.example.com";
</script>
<h1>JavaScript Variables</h1>
<p>the href below should link to http://www.example.com</p>
<script>
document.write('Open Here');
</script>
<p>this is after the link</p>
Via the DOM
Put an id on the link:
Open here
and then in a script tag after it
document.getElementById("burl").href = burl;
Live example:
<script>
var burl = "http://www.example.com";
</script>
<h1>JavaScript Variables</h1>
<p>the href below should link to http://www.example.com</p>
Open Here
<p>this is after the link</p>
<script>
document.getElementById("burl").href = burl;
</script>
Re your comment:
what if...I want to manually add an extra element to each link <a href="burl-string-here/extra-link-element"
I'd use a data-* attribute (data-extra, whatever) on the links to say what the extra was. Then get the element into a variable, then:
link.href = burl + link.getAttribute("data-extra");`
I wouldn't put the extra in href because some browsers try to expand href even when you get it via getAttribute (though they shouldn't).
You've said "each link" which makes me think you have a bunch of them. If so, don't use an id, but a class instead:
<script>
var burl = "http://www.example.com";
</script>
<h1>JavaScript Variables</h1>
<p>the href below should link to http://www.example.com</p>
<p>First link</p>
<p>Second link</p>
<p>Third link</p>
<p>this is after the link</p>
<script>
(function() {
Array.prototype.forEach.call(document.querySelectorAll("a.burl"), function(link) {
link.href = burl + link.getAttribute("data-extra");
});
})();
</script>
That uses Array#forEach which is on all modern browsers, but not (say) IE8. It can be shimmed/polyfilled, though, or you can use a simple for loop. Options in this other answer (see "for array-like objects" as the list we get back from querySelectorAll is array-like).
is it, what u want?
$(document).ready(function(){
var burl = "http://www.example.com";
$('a').attr('href', burl);
});
ps using jQuery.
if you are using jQuery.
<script>
$(document).ready(function(){
var burl = "http://www.example.com";
$('a').attr('href',burl )
});
</script>

How can I save the contents of a textarea as a variable using javascript in an external document?

I have tried, as many have suggested, saving a variable as the .value or .innerHTML of an ID, found by using document.getElementById. Here is all of my HTML:
<html>
<head>
<title>write</title>
<script type="text/javascript" src="g.js"></script>
<link rel="stylesheet" type="text/css" href="g.css" />
</head>
<body>
<div id="box">
<textarea id="txt" placeholder="placeholder. type here.">text text</textarea>
</div>
</body>
</html>
and here is my javascript, currently meant to fire an alert that contains the text in the text area – right now that would be, text text:
function run(){
var txt = document.getElementById('txt');
alert(txt);}
run()
Right now, loading the page fires an alert with the text Null and adding .value after getElementById('txt') results in no alert. Many thanks in advance.
The problem is that your javascript is executing before the DOM is constructed. When you load the JavaScript file in the <head> of the document, it is executed immediately, before the <textarea> tag has been created.
Try moving your script block below the textarea, just before the </body> tag.
Here's an example: fiddle
After the DOM is constructed you can use getElementById just as have and can access the contents of the textarea with the value attribute. All of this is in the fiddle above.
Alternatively, you can wrap your run() method call with a library that provides an event when the DOM becomes ready. jQuery's example would be:
$(function () {
// code you want to execute when the DOM is ready.
run();
});
function run() {
var txt = document.getElementById("txt").value;
alert(txt);
}
$(document).ready(function(){
run();
});
check this jsfiddle link
You are not getting textarea value because your javscript function is getting executed before there's value in DOM
or using javascript
function run(){
var txt = document.getElementById("txt").value;
alert(txt);
}
window.onload = run();
More about window.onload
The javascript below works in firefox. In fact, if you click the answer button for this question, you can try it out in firebug on this very page...
var textArea = document.getElementById("wmd-input"); // #wmd-input is the text input where your answer goes...
alert( textArea.value );
Make sure you enter some text first, of course.
While you're at it, you should give jQuery a try:
alert( $("#wmd-input").val() );
Or better yet,
console.log($("#wmd-input").val());
Hope that helps.

Manipulating DOM with (framework-less) javascript

Ok, I haven't been using JavaScript without JQuery for quite some time now... But, as coding goes, I have to do without it's power for a project where I can't be sure that JQuery is provided.
The thing I'm trying to do would be the following using JQuery:
$(document).ready(function() {
$('#myDiv').append('<ul><li>a</li><li>b</li></ul>');
});
Now to the non-jquery thing, this is what I have and I really can't understand why it isn't working:
<html>
<head>
<script type="text/javascript">
function load() {
var s = '<ul><li>a</li><li>b</li></ul>';
var element = document.getElementById("myDiv");
element.innerHtml += s;
}
</script>
</head>
<body onload="load()">
<div id="myDiv"></div>
</body>
</html>
Thing is, nothing happens (the function gets called though). Could it be that the DOM isn't ready when load() is called?. I vaguely remember this code working in the firefox 2.x IE7 era ...
What would be the (a) right solution?
It's innerHTML not innerHtml. Notice the upper case HTML. Change that and it should work fine! Here's a working example.
By using innerHtml you are simply creating a new property on the element object and giving it the value of s.
<html>
<head>
<script type="text/javascript">
function load() {
var s = '<ul><li>a</li><li>b</li></ul>';
var element = document.getElementById("myDiv");
element.innerHTML += s;
}
</script>
</head>
<body onload="load()">
<div id="myDiv"></div>
</body>
</html>
JS is case sensitive
I think you want element.innerHTML += s;.

Categories

Resources