function to exchange tags - javascript

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>

Related

click event on each button of a class (chess viewer)

First time writing here. I am new to programming and here I am learning a lot of things!
Now, I want write this: for each clicked element of a class create a var with nextSibling's text and show it somewhere. The following code is for sure full of error, but it is what i thought:
//wants to create an accessible variable (even out the function)
//from a sibling element's text.
$(".games").click(function(){
myVar = this.next("p").html;})
the HTML situation is this:
<button class="games">GAME ONE</button><p> THESE ARE THE DETAILS OF THE GAME 1</p>
<button class="games">GAME TWO</button><p> THESE ARE THE DETAILS OF THE GAME 2</p>
<div id="show"> I will show the content of paragraphs here if one of the two buttons is clicked</div>
I thank everybody because - I repeat - I am learning a lot here.
EDIT
Thanks everybody for the answers. I am trying something related to your suggestions, but i think the problem should be another because actually I am working with chessJS and chessboardJS to make a page where show the moves of a chess game in a chessboard. But, when I try to say that myVar (where there is the moves list to pass to the chessJS function load_pgn) is the content of one id like this:
<p id="theGame">1. e4 e5</p>
// myVar contains the moves list
var myVar = $("#theGame").html();
Chess().load_pgn(myVar);
all works fine, but I cannot make it work by saying that: for each clicked element (of a class, maybe) myVar is the html value of the clicked element. Furthermore in the console I receive an error that says that pgn_replace is not a function.
<p class="someGames">1. e4 d5 2 Nf3 Nc6</p>
<p class="someGames">1.d4 e5</p>
Maybe I explained the fact a bit bad. this is it. Thank you again for the answers.
FINAL EDIT
Thanks to your answers and other discussions on the site I managed to find a solution to take the text of one element of a class and store in a var with the following code:
$('.class').click(function(){
this.textContent = $(this).html();
var myVar = $(this).html();})`
Thank you!
function buttonClick(button){
document.getElementById("show").innerHTML=button.innerHTML
}
<button class="games" onclick="buttonClick(this)">GAME ONE</button><p> THESE ARE THE DETAILS OF THE GAME 1</p>
<button class="games" onclick="buttonClick(this)">GAME TWO</button><p> THESE ARE THE DETAILS OF THE GAME 2</p>
<div id="show"> I will show the content of paragraphs here if one of the two buttons is clicked</div>
const button = document.querySelector(".games")
button.addEventListener('click', () => {
myText = document.querySelector('p').innerHTML = 'your text : I will show the content of paragraphs here if one of the two buttons is clicked '
)
<button class="games">GAME ONE</button><p> THESE ARE THE DETAILS OF THE GAME 1</p>
<button class="games">GAME TWO</button><p> THESE ARE THE DETAILS OF THE GAME 2</p>
<div id="show"> <p> I will show the content of paragraphs here if one of the two buttons is clicked </p></div>

JavaScript: transform a text between <p> tags into a new one also between <p> tags (output)

I'm trying to operate a transformation onLoad from a <p> text </p> in order to create a <p> new modified text </p> (the point is I don't wanna use textareas) in simple javascript.
Here is what I've been trying to do (but it seems to work only with values coming from textareas) :
<script>
<?php include("js/roman.js"); ?>
function afficher(form2) {
var testin = document.form2.TextToModify.value;
document.form2.NewModifiedText.value=hangul_to_roman(testin);
}
</script>
<div>
<p name="TextToModify" value="input" onLoad="afficher(form2)">
TEXT
</p>
<p name="NewModifiedText" value="output">
<!-- NEW MODIFIED TEXT -->
</p>
</div>
Does anyone know how to get the first text between the "p" tags in order to proceed to the transformation ?
Thank you in advance !
Some notes:
Better avoid inline event handlers.
p elements can't have name nor value attributes.
document.form2.TextToModify is a non standard way of accessing a form element. The standard way would be document.forms.form2.elements.TextToModify, but it won't work because p elements aren't listed elements.
function hangul_to_roman(str){ return str; }
function afficher() {
document.getElementById('NewModifiedText').innerHTML = hangul_to_roman(
document.getElementById('TextToModify').innerHTML
);
}
afficher(); // This must run after loading the DOM
<div>
<p id="TextToModify">
TEXT
</p>
<p id="NewModifiedText">
<!-- NEW MODIFIED TEXT -->
</p>
</div>
The hangul_to_roman is only included here in order to make the code snippet runnable.
Note afficher() must be called after your elements have been loaded, e.g in a script placed just before closing </body>, or in an event listener of DOMContentLoaded or load events.

Javascript Targeting Child Elements in a ID

i'm currently learning javascript and had a question.
I am trying to target only the h1 tag in the div id=title i tried a few ways using this as a reference site amongst others: http://www.ibm.com/developerworks/library/wa-jsanddom-pr/sidefile1.html
but nothing seems to be working, i get back the value "undefined"
esentially what i want to do is only target the h1 and change the text to something else.
how do i do that? is this along the right path or is there a different way to do it?
<div id="title">
<h1>Javascript Lesson 1</h1>
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.firstChild;
console.log (title.value);
</script>
any help is greatly appreciated. Thanks.
Take a look at Element.getElementsByTagName.
var titleElement = document.getElementById("title");
var titleChildren = titleElement.getElementsByTagName("H1");
// Do something with children.
// In your example code, you'll only have one element returned
console.log(titleChildren[0].innerHTML);
// To change the text, simply access the innerHTML property
titleChildren[0].innerHTML = "[New Value]"
Here's a working fiddle to play with.
If you know that the h1 you want to modify will always be the first h1 child you could do something like this:
<script>
document.getElementById('title').getElementsByTagName("h1")[0].innerHTML = "New Name";
</script>
The first child of the <div> (in your example) is a text node. Text nodes don't have a value property. Even if you remove the whitespace between the <div> and the <h1> to make it the first child node, the <h1> still doesn't have a value property. What it does have is a child text node with the node value "Javascript Lesson 1".
What you want is to retrieve a reference to that text node, and its value. There are different ways to do this. For instance:
<div id="title">
<h1>Javascript Lesson 1</h1> <!-- White space before <h1> -->
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.childNodes[1];
console.log (titleHeading.firstChild.nodeValue);
</script>
or:
<div id="title"
><h1>Javascript Lesson 1</h1> <!-- No white space -->
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.firstChild;
console.log (titleHeading.firstChild);
</script>
or:
<div id="title">
<h1>Javascript Lesson 1</h1>
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.getElementsByTagName('h1')[0];
console.log (titleHeading.innerHTML);
</script>
or some permutation of the above.
You can get a collection of children back with Document.querySelectorAll(). Here are two examples:
var matches = document.querySelectorAll("iframe[data-src]");
var matches = document.querySelectorAll("div.note, div.alert");
As you can see, it is nearly JQuery like. Notice the comma in the second example. JQuery would use a space there. These examples were taken from developer.mozilla.org.
If you don't want a collection, (if you want a single element) document.querySelector("#myCSSSelector"); is what you want.

does innerHTML get rid of elements entirely?

EDIT: I figured it out, thanks for your time!
I have a div with an id of container and three buttons above that.
When a user clicks any of the buttons above, then javascript replaces the contents of the div according to the buttons pressed using innerHTML.
Clicking on each button once works fine because I'm just replacing the elements in the div. But when I try to reclick the buttons my console prints out 'Uncaught TypeError: Cannot read property 'innerHTML' of null '
So I'm assuming innerHTML gets rid of the elements entirely. Is there a way to retrieve those elements so I can constantly click the buttons and have the respective elements appear?
If not, I was thinking of having a div for each button in my html file and then using display:none. When a user clicks on any of the buttons, the div for that button will be set to display:block.
***Edit****. I believed I answered my own question.**
Yes, using innerHTML does get rid of previous elements inside the div container. Therefore, if you wanted to grab those elements again, you can't. and the above error will be printed in the console.
JsFiddle : http://jsfiddle.net/7Q4vD/
<div id="buttonNav">
<button id="button1">1</button>
<button id="button2">2</button>
<button id="button3">3</button>
</div>
<div id="container">
<p id="para">Data in paragraph</p>
</div>
I Tried the following, and it worked perfect, check it:-
<button type="button" id="red"onclick="myFunction(id)"> Red!</button>
<button type="button" id="blue"onclick="myFunction(id)"> Blue!</button>
<button type="button" id="green"onclick="myFunction(id)"> Green!</button>
<div id="container"></div>
<script>
function myFunction(e){
document.getElementById('container').innerHTML = e
}
</script>
Ok, now got the problem.
You're writing:-
<div id="container">
<p id="para">Data in paragraph</p>
</div>
and then,
var container = document.getElementById('container');
and then you're setting the innerHTML with a sring:-
container.innerHTML = data;
So, suppose data = "abc";
The your html becomes
<div id="container">
abc
</div>
So, the p tag is not present here.
Thus when you're try the following in the next time:-
document.getElementById('para').innerHTML = data2;
It's not getting anything and showing the error.
Either you replace
document.getElementById('para').innerHTML = data2;
with
container.innerHTML = data2;
And remove the p tag from your html, or write:-
var para= document.getElementById('para');
and then write the following in respective cases:-
para.innerHTML = data2;
para.innerHTML = data;

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

Categories

Resources