I am currently working on a on a small project, if you can call it that way.
It’s pretty simple two buttons which affect a <p>
element that alone works, but now I decided to use Objects and DOM to get a better understanding of it. So I added a ranking below the p which should call 1st, 2nd… and so on depending on which number you are.
HTML
<body>
<div id="OuterShell">
<div id="ContainsButtons">
<button id="AddPs">Add</button>
<button id="RemovePs">Remove</button>
</div>
<div id="ContainsPs">
<p id="text" class="text">0</p>
</div>
</div>
<script src="./TestJS.js"></script>
</body>
Now my problem is that it either deletes the new ranking which I currently added, deleting everything or deleting nothing at all and just add more and more paragraphs.
JS
var Text = document.getElementById("text");
var B1 = document.getElementById("AddPs");
var B2 = document.getElementById("RemovePs");
var div1 = document.getElementsByTagName("div")[2];
var counter = 0;
var x = false;
function AddOne() {
if (counter < 10) {
counter++
update();
} else {
Text.innerText = TextStored.Limit;
}
}
function RemoveOne() {
if (counter > 0) {
counter--
update();
} else {
Text.innerText = TextStored.Limit;
}
}
function update() {
Text.innerText = counter;
var ranking = document.createElement("p");
var ItsText = document.createTextNode(TextStored.Text[counter]);
ranking.appendChild(ItsText);
div1.appendChild(ranking);
if (x) {
var deleted = ranking.parentNode;
deleted.removeChild(ranking);
}
x = true;
return ranking;
}
var TextStored = {
Text: [0, "1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"],
Limit: "You reached the limit"
};
B1.onclick = AddOne;
B2.onclick = RemoveOne;
I tried it first myself different placing of the code, use different variables even tried to solve it in a complicated way which doesn’t work either then I looked it up online at the end but I didn’t found something useful (or didn’t understand/google it right.
Nothing worked I only got a better understanding why it doesn’t work and how the PC reads the code.
##Expections
When I press one button (for example Add) it should output this
1
1st
When I press Add again it should update both numbers
2
2nd
I am not able to update the second one and don’t know what to do.
2
Answers
You’re complicating things a little, you already have the knowledte on hot to change text of an element, no need to create one, query it etc etc. Define it in HTML (
<div id="rank">
) and access it via JS. Also use ratheraddEventListener
instead of the overridingon*
handler.Notice the new element in HTML and the updated
update()
function:The example below adds and removes the number value by one with the corresponding
<button>
, it’s minimum value is 0 and it has no maximum. Details are commented in example.