does innerHTML get rid of elements entirely? - javascript

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;

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>

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).

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>

Show all dropzone errors instead of one at a time [duplicate]

I have this HTML:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
</div>
and want to add more divs after the strong element to result:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
<div> ... </div>
<div> ... </div>
<div> ... </div>
</div>
I am trying this:
var row_str = '<div>content here</div>';
$('#region_North_America div:last').html(row_str);
However, there is no change to the html. This is probably so since there is no div within the element selected.
I know that the js is making it to this code because I can print the content of row_str to the console.
So, how can I get to the end of that container element to add the new items?
Thx.
Try:
$("#region_North_America").append(row_str);
using append().
Or:
$("<div>content here</div>").appendTo("#region_North_America");
To create the element on the fly, and place it in the document.
Using the appendTo method.
Your code will just place html in the last div within #region_North_America. Use the append function.
$("div.region-list").append(row_str);

show element not working

Hi I have a problem with my function, when I call it to show my hidden div it does not work. It does not show the hidden div. I followed previous examples from what have been posted in stackoverflow but still my code does not work.
This is my html file
<div id="playTheGame" class="css/outer" style="display:none;" >
<div class="css/inner">
<h1>Choose!</h1>
<section id="hand">
<img src="images/rock.png">
<img src="images/paper.png">
<img src="images/scissors.png">
</section>
</div>
</div>
My Function
<script>
function logSuccess(){
document.getElementById("playTheGame").style.visibility="visible";
}
</script>
The Button I used for the function
<input type="button" onclick="logSuccess()" value="Show">
Change your code to this
document.getElementById("playTheGame").style.display = "block";
Since you hid it using the display property, show it using the display property.
There are two options for this:
One using JavaScript:
object.style.display="block"; // where object will be the playThemGame id element..
And the other one using jQuery; JavaScript library.
$("#playTheGame").show();
The option two won't work, because you will have to write the event function too, So just use the first one as:
document.getElementById("playTheGame").style.display="block";
Edit:
Since you are using
document.getElementById("playTheGame").style.display="block";
To disply the result, then you must use this to remove the display!
document.getElementById("playTheGame").style.display = "none"; to hide it back!
The basic idea is that, this will just shift the object-->style-->display's value to none Its not going to add any more attribute. Its just going to shift current attribute's value.

Categories

Resources