Javascript text printing order - javascript

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

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.

Why won't all the ids get changed though I selected all of them by using the # idname?

I am completely new to coding in general. I've started with the very basics of HTML, CSS and JavaScript.
I have two paragraphs:
<p id="title1">Change this</p>
<p id="title1"> Change this too! </p>
While the first one gets automatically changed by:
<script type="text/JavaScript">
$('#title1').html('Changed!');
</script>
the second one doesn't. But shouldn't it? Since all #title1 are being changed?
I have the same problem for the onclick version. The first paragraph gets changed when clicking on it, the second doesn't.
<p id="title3" onclick="sayGoodbye();">Toggle this Hello - Goodbye</p>
<p id="title3" onclick="sayGoodbye();">Thing to click on</p>
<script type="text/javascript">
function sayGoodbye(){
$("#title3").html('Goodbye');
$("#title3").click(function(){
$("#title3").html("Hello again!");
$("#title3").off("click");
});
}
</script>
When you select an element by its id, only the first one gets selected because you're only supposed to use one id on one element! Each id should only ever be used once on a page!
If you need to get a bunch of elements together 'by' something, do it 'by class'.
$(".title1").html("Changed!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title1">Change this</p>
<p class="title1"> Change this too! </p>
ID attribute has to be unique for each HTML tag. You can use class attribute to act on multiple tags.
The id attribute should be unique at least in the same level child tree.
Use class instead and listen to .click() with $(this) to get
current clicked element.
If you want to call a function using onclick attribute pass clicked element to it using this like onclick="sayGoodbye(this);".
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title3" onclick="sayGoodbye(this);">Toggle this Hello - Goodbye</p>
<p class="title3" onclick="sayGoodbye(this);">Thing to click on</p>
<script type="text/javascript">
function sayGoodbye(t){
$(t).html('Goodbye');
$(t).click(function(){
$(this).html("Hello again!");
$(this).off("click");
});
}
</script>

function to exchange tags

I have following paragraph in html code:
<p id=tag1> html statements before click </p>
... and I am trying to write function which would split the above paragraph to two paragraphs like this :
<p id=tag1> html statements after click </p><p id=tag2></p>
... with intention to exchange then tag1 id with tag2 id to have final result:
<p id=tag2> html statements after click </p><p id=tag1></p>
I am trying to achieve desired result by this function:
&ltscript>
function myFunction() {
document.getElementById("tag1").innerHTML = "html statements after click &lt/p>&ltp id='tag2'>";
document.getElementById("tag2").id = "tagTmp";
document.getElementById("tag1").id = "tag2";
document.getElementById("tagTmp").id = "tag1";
}
&lt/script>
... but this donesn't work to me. Problem is with the first step - innerHtml modification works different ways as expected and yealds following result:
<p id=tag1> html statements after click
<p></p>
<p id=tag2></p>
</p>
... paragraph id=tag2 is still nested inside paragraph id=tag1 (I want to have the both paragraphs at the same level).
Is there any way to get requested functionality? Can you help please?
Thanks.
document.getElementById("tag1").innerHTML = "html statements after click </p><p id='tag2'>";
So the reason this is not acting as you expect it to is because this is not changing the markup, as you think it is. innerHTML does not include the open and close tags. Your interacting with a dom node, so you can't close the parent node like that. As you can see it tries to protect your weird request of a single </p> and creates a new open for it so it's paired.
If you were going to do this with jquery, as that's one of your post tags, it could possibly be something like...
//get the existing element
var $originalTag = $('#tag1');
//update its id
$originalTag.prop('id', 'tag2');
//create a new one after it with the original id
$('<p id="tag1"></p>').insertAfter($originalTag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="tag1">An Existing Tag</p>
Here is a sample code for you
<html>
<div>
<p id=tag1> html statements before click </p>
</div>
<script>
var
p = document.querySelector('p'),
p2 = document.createElement('p');
p2.id = 'p2';
p2.textContent = ' p2...p2 '
p.outerHTML += p2.outerHTML;
</script>
</html>

what is the most straightforward way of writing the content of a variable to page?

I have a <p></p> and I want to put a text inside it a text that a JS variable holds,
is it possible to put a <script> inside the <p> and just write it there, without using any kind of DOM searching (not even innerHTML)?
<p>
<script>
var theVariable="this has some content";
document.write(theVariable);
</script>
</p>
hope that helps and is what you wanted.
Demo

Categories

Resources