innerHTML replaces whole document - javascript

I have a setInterval function which replaces text within a particular div element every second. I also have text in the body which I want to keep.
What is the easiest way to preserve the text in a document without .innerHTML overriding the whole document?
<html>
<div id="timer" </div>
<script>
window.onload = setInterval(function(){refreshTime()},1000);
function refreshTime()
{
document.getElementById("timer").innerHTML = ""+DAYS+" Days:"+HOURS+" Hours:"+(minutes)+" Minutes:"+seconds+" ;
time = time+1;}
</script>
<body>
<p>
sOME TEXT I WANT TO KEEP ON
</p>
</body>
I've removed a lot of unncessary code to make it easier for you guys to read. I hope you guys understand what I'm asking. This is my first time on SO

<div id="timer" </div>
change it to <div id="timer"></div>
And paste it in body tag

Related

Copy/Clone div content to another div

I need to copy content from div1 and paste/append it to div2 by click. Then if I change content in div1 and click the button again the content should go to div3 without changing the content in div2. This is what I found so far.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="$('#div2, #div3').html($('#div1').html());">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
Because I assign value it would paste the same in both divs and I have no idea how to do it separately. I guess some loops will be needed.
Is it possible and if it is could somebody give me some ideas or links to read materials. Thanks in advance!
You can use a variable to store the number of the div element and then increment it accordingly. (Here I am assuming only div2 and div3 are there)
Since you have not mentioned how the value of div1 is going to update. I am manually doing it using $('#div1').html("New Value"); inside the function add().
<html>
<body>
<body>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="add()">Copy</button>
<div id="div2"><p>div1 Placeholder</p></div>
<div id="div3"><p>div2 Placeholder</p></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var n = 2;
function add(){
$('#div'+n).html($('#div1').html());
$('#div1').html("<p>New Value</p>");
n++;
}
</script>
</body>
</html>
Try running the snippet. Clicking the button once will put the value of div1 to div2 and then it changes the original content of div1 to New Value. Again if you click the button, the new value of div1 i.e., New Value will be put to div3.
Though this will also try to update div1 again to New Value, which won't make any change. It would be better if you write some other ways to update the div1 element.
Take care of the <p> tag if you want it to be retained. Well, that also depends on the way you update the value of div1.
To append you can use $('#div'+n).append($('#div1').html());
I wrote a little help code to get you started. So what i did was to move the logic to a function which iterate a variable i (which can only take the value 2 and 3). This does not check if the text has changed and will overwrite div2 and div3 in turns on every click (remove if test if you only want to do it once).
<html>
<body>
<body>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="copyPaste()">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
var i = 2;
function copyPaste() {
//add logic to check if text has changed before executing next line
$(`#div${i++}`).html($('#div1').html());
if(i < 3) i = 2;
}
</script>
</body>
</html>
Using a script tag with javascript code as in Saif's answer is perfectly valid (you only should be careful not to overwrite the global var used to keep count). To be more inobtrusive the click event could also be added in the script tag.
As another possibility with the opposite approach, you could do all in the the button attributes, using jQuery's data. The count is here stored in an attribute in the button, but it could also be stored in the original div #div1. The code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="$('#div' + $(this).data('targetdiv')).html($('#div1').html()); $(this).data('targetdiv', $(this).data('targetdiv') + 1);" data-targetdiv="2">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
Some important notes about data: using data to change the value doesn't update the DOM attribute itself, because once the value is retreived from the attibute, jQuery uses an internal javascript code to keep the value. There's no real need to udate the DOM, but if you really want it to, you can use attr instead of data. But if you use attr, never mix it with calls to data, as the latter won't see the DOM updates after the first time it has retreived the value (because it uses the value stored in the internal javascript cache instead of reading the DOM attribute).

How to replace a <p> tag in an html file using Javascript

In an Html file that I have, there is a paragraph tag that basically looks like this:
<p class="col-sm-8 form-control-static wordwrap">
Hey
What's
Up
</p>
The contents of this paragraph are grabbed from a textarea that a user fills out and the value of this textarea is grabbed via jquery and filled into this element.
The output looks like this: Hey What's Up
This paragraph tag ignores the newlines within the paragraph, so the paragraph displays all on one line. Due to the format and layout of the project, I can't necessarily change the html source. I was wondering if there was a way to change this exact element to be:
<pre class="col-sm-8 form-control-static wordwrap">
Hey
What's
Up
</pre>
using only javascript. Is this possible? This is so my output will keep the newlines.
I think you are looking for something like this. you tagged jquery so I used that but this could be done in vanilla js too.
I linked to a onkeyup event if you wanted to change to use the button only if you wanted
$(document).ready(function(){
function updateContent() {
$('#p1').html($('#source').val());
}
$('#update').on('click', function(e){
updateContent();
// add other stuff here
// for only the click event
})
$('#source').on('keyup', updateContent);
})
button {
display:block;
}
#source {
height:100px;
}
#p1{
white-space:pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="source" placeholder="Update content and click 'update'">new content
add line breaks and <p>html markup</p>
</textarea>
<button id="update" >Update</button>
<p id="p1">THIS WILL CHANGE!</p>
It is very simple and has been asked before... BUT here it is, using DOM:
document.getElementById("p1").innerHTML = "<p>This</p><p>Has</p><p>Changed!</p>";
<p id="p1">THIS WILL CHANGE!</p>
So your piece of code you need is:
document.getElementById("p1").innerHTML = "New text!";
EDIT
This is simpler, easier and more browser friendly than using <pre> tags. Therefore, I would highly recommend you to use this instead.

Javascript text printing order

Just beginning to learn JavaScript, have written below simple code to print out text and testing it in Browser.
the output is :
This is from a javascript function...
This is my test heading
But I was trying to change the order(swap the two sentences printed) of the sentences being printed to:
This is my test heading
This is from a javascript function...
What changes are needed in the below code to print the text printed in above order.
<!DOCTYPE html>
<html>
<body>
<p id="demo">This is a paragraph.</p>
<p id = "demo1">This is demo1.</p>
</body>
<script>
//document.write("<h3>This is my test heading</h3>");
document.getElementById("demo1").innerHTML="This is my test heading";
</script>
<script>
//alert("My First JavaScript");
displaytext();
function displaytext()
{
document.getElementById("demo").innerHTML="This is from a javascript function...";
}
</script>
</html>
In HTML, the order of JavaScript functions doesn't matter as much as the order in which you have put your HTML Elements.
http://jsfiddle.net/3CpU7/
The above fiddle has your answer: you have to switch the DIVs.
<p id = "demo1">This is demo1.</p>
<p id="demo">This is a paragraph.</p>
Also, keep in mind - You can use CSS to create whatever behaviour you want for DIVs (e.g. float, clear, position, etc.)
EDIT:
What also is another obvious way to do it is, if you don't want to change your HTML Markup, is interchange the content of the DIVs as this:
(Another fiddle for this: http://jsfiddle.net/3CpU7/1/)
document.getElementById("demo").innerHTML="This is my test heading";
displaytext();
function displaytext()
{
document.getElementById("demo1").innerHTML="This is from a javascript function...";
}
Hope it helps your initial learning. :)
Switch the HTML element's id. As the function name implies, the getElementById function gets you the HTML element with the given id (if exists, else null).
This
document.getElementById("demo1")
refers to
<p id="demo1">This is a paragraph.</p>
And
document.getElementById("demo")
refers to
<p id="demo">This is demo1.</p>
Since the elements in your HTML are in the order
<p id="demo1">This is a paragraph.</p>
<p id="demo">This is demo1.</p>
you must target demo1 to change the first and demo to change the second paragraph's inner HTML.
Thus, either change the ids in your JS function call, or in your HTML.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById

body.innerHTML before/after nth-child

Is it possible to add something with innerHTML before/after the nth child of <body>?
e.g.:
<html>
<head></head>
<body>
<div id="first">First</div>
<div id="second">Second<div id="second_sub"></div></div>
<div id="third">Third</div>
</body>
</html>
I can add at the beginning with body.innerHTML = html + body.innerHTML and at the end with body.innerHTML += html but how to add, for example, before the second <div>?
I don't want to use replace on <div id="second"> as the source changes and the insert should be done at random. Is there a solution with innerHTML or do I need to switch to Dom Nodes? Would be slow in old browsers :(
You are probably looking for the insertBefore method. It will insert a child before the given element. Alternatively there's the appendChild method which will always push elements on the beginning of the given element.
Examples:
<body>
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
Let's assume we're inserting a new element stored in the var newElem:
document.insertBefore(newElem, document.getElementById("elem2")) will give:
<body>
<span id="elem1">Hello</span>
<!-- New element here! -->
<span id="elem2">World</span>
</body>
document.appendChild(newElem) will give:
<body>
<!-- New element here! -->
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
I'm using this by now (Thanks to ajax333221):
e = document.createElement('div');
e.innerHTML = '<div>... huge content with several sub elements ...</div>';
document.body.insertBefore(e, document.body.childNodes[2]);
This is a combination of both techniques. With this I'm able to use the fast .innerHTML without extremely blowing up the code with createElement(), setAttribute(), etc.
Other solutions are welcome.

Is my text indexed by Google?

I am making a HTML page, with JavaScript. In the HTML is the first content of a div, but when the user clicks a button, the text changes.
The text in the div is actual content, and needs to be findable by Google. The text is now stored in a simple variable in the JavaScript file.
Questions:
- Is that text indexed?
- Are there any better ways to store the text?
You can keep the text in a div and then change the visibility to hidden
<div id="content" style="visibility: hidden;">
Div content
</div>
Then in javascript,
document.getElementById("content").style.visibility="visible";
should make the document visible. Since the text will be there in the source for the page, it will be indexed by google, but will be displayed only when you run that line of javascript.
Storing the text in js variables is generally not a good idea.
You can put this text in a hidden div instead, like this:
<div id="target">
super-text
...
</div>
<div id="second">
super-mega-text
...
</div>
<button onclick="replace_text();">
<script type="text/javascript">
function replace_text() {
var target = document.getElementById('target');
var second = document.getElementById('second');
target.innerHTML = second.innerHTML;
}
</script>
In that case your second text will be indexed by Google.
Of course you better use any js framework like jQuery or Mootools.
Mootools example:
<div id="target">
super-text
...
</div>
<div id="second">
super-mega-text
...
</div>
<button id="button">
<script type="text/javascript">
window.addEvent('domready', function(){
$('button').addEvent('click', function(){
$('target').set('html', $('second').get('html'));
});
});
</script>
Javascript is not searched, see googles answer:
http://www.google.com/support/customsearch/bin/answer.py?answer=72366
I found a good article about hide/display content only with CSS. It's working without Javascript: http://www.devinrolsen.com/css-hide-and-display-content/

Categories

Resources