Turning an ordered list into a table - javascript

Still pretty new at JavaScript. I'm trying to write a program where you replace an ordered list with a table. The table should have 2 columns and 3 rows. The first column has the numbers(1,2,3) and the right column has the names of the games. How do I get the table to replace the list and read the list items?
Here is the JSFiddle: http://jsfiddle.net/gmpc0acd/74/
HTML
<html>
<head>
<style>
table,td
{
border:1px solid black;
}
</style>
</head>
<body>
<p>Top Games</p>
<ol id="list">
<li id="element1">Halo</li>
<li id="element2">Portal</li>
</ol>
<button onclick="addNewGame(); this.disabled=true">Insert</button>
<button onclick="tableCreate()">Replace</button>
JavaScript
function addNewGame() {
let ol = document.getElementById("list");
let li = document.createElement("li");
li.appendChild(document.createTextNode("Rocket League"));
ol.appendChild(li);
list.insertBefore(li,list.childNodes[2]);
}
function tableCreate()
{
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.createTextNode("want game names in here");
z.appendChild(t);
document.getElementById("myTr").appendChild(z);
}

I have added a div 'id' - 'tryme' and inside i got the list.
so when you click 'replace' it should clear the div using innerHtml and then build the table. ( appending the 'tryme' div )
edited
To get 'ol' children use
let elmList = document.getElementById('list').children;
now you can iterate it like an array and use its 'innerText'/'innerHtml' as you like.
In my example before clearing 'tryme' i have an array with the lists children.
as displayed in the console.
let trymeDiv = document.getElementById("tryme");
trymeDiv.innerHTML = "";
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.getElementById('tryme').appendChild(x)
<p>Top Games</p>
<div id="tryme">
<ol id="list">
<li id="element1">Halo</li>
<li id="element2">Portal</li>
</ol>
</div>
<html>
<head>
<style>
table,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Top Games</p>
<div id="tryme">
<ol id="list">
<li id="element1">Halo</li>
<li id="element2">Portal</li>
</ol>
</div>
<button onclick="addNewGame(); this.disabled=true">Insert</button>
<button onclick="tableCreate()">Replace</button>
</body>
</html>
<script>
function addNewGame() {
let ol = document.getElementById("list");
let li = document.createElement("li");
li.appendChild(document.createTextNode("Rocket League"));
ol.appendChild(li);
list.insertBefore(li, list.childNodes[2]);
}
function tableCreate() {
let elmList = document.getElementById('list').children;
arrayOfGames = [];
for ( var i = 0; i < elmList.length; i++){
arrayOfGames.push(elmList[i].innerText);
}
console.log(arrayOfGames);
let trymeDiv = document.getElementById("tryme");
trymeDiv.innerHTML = "";
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.getElementById('tryme').appendChild(x);
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.createTextNode("want game names in here");
z.appendChild(t);
document.getElementById("myTr").appendChild(z);
}
</script>

Related

how the append method works on html template tag?

i am trying to add the content present inside of html template tag inside of both div_1 and div_2 but it gets added only inside div_1, whats wrong in my code please evaluate.
html code
<!DCOTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<template>
<h2>Grocery Item</h2>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</template>
<div id="main-div" style="display: 1px solid black;"></div>
<div id="another-div style="display: 1px solid black;"></div>
<script>
const template = document.querySelector("template");
const tempBody = document.importNode(template.content, true);
const list = tempBody.querySelectorAll("li");
for (let i = 0; i < 3; i++) {
list[i].textContent = "Item - " + ( i + 1 );
}
const div = document.getElementById("main-div");
const div_1 = document.getElementById("another-div");
div.append(tempBody);
div_1.append(tempBody);
</script>
</body>
</html>
Thanks in Advance.
You can try the following way:
<template>
<h2>Grocery Item</h2>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</template>
<div id="main-div" style="display: 1px solid black;"></div>
<div id="another-div" style="display: 1px solid black;"></div>
<script>
const template = document.querySelector("template");
//div_1
let tempBody = document.importNode(template.content, true); // declare with var or let
updateTemplate(tempBody);
const div = document.getElementById("main-div");
const div_1 = document.getElementById("another-div");
div.append(tempBody);
//div_2
tempBody = document.importNode(template.content, true);
updateTemplate(tempBody);
div_1.append(tempBody);
//function to populate tempBody
function updateTemplate(tempBody){
const list = tempBody.querySelectorAll("li");
for (let i = 0; i < 3; i++) {
list[i].textContent = "Item - " + ( i + 1 );
}
}
</script>

JavaScript: Node List to Array Conversion

I am trying to convert Node List to Array. I want to print the list (caption 1,...caption 5), but it prints:
[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement]
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Caption</title>
<style>
.captn {
position: absolute;
padding: 10px;
margin: 200px auto;
text-align: center;
font-family:serif, fantasy;
font-size:36px;
color: #009933;
text-decoration: none;
text-transform: uppercase;
list-style-type: none;
}
</style>
</head>
<body>
<div>
<ul id = "caption" class="captn"><li id = "caption0">caption 0</li><li id = "caption1">caption 1</li><li id = "caption2">caption 2</li><li id = "caption3">caption 3</li><li id = "caption4">caption 4</li><li id = "caption5">caption 5</li></ul>
</div>
<script>
var msg;
var cap = [];
var capList;
var f = document.getElementsByClassName("captn");
msg = f.item(0).childNodes;
b = f.item(0).childNodes.length;
var classAr = Array.prototype.slice.call(msg);
document.write(classAr);
</script>
</body>
</html>
Use querySelectorAll and select all elements under class captn with an id beginning with caption, then convert the node list to array usingArray.from and lastly map through the array, returning a new array containing only the textContent
var captions = Array.from(
document.querySelectorAll('.captn [id^="caption"]')
);
var captionsText = captions.map(function(caption) {
return caption.textContent;
});
document.write(captionsText);
<div>
<ul id="caption" class="captn">
<li id="caption0">caption 0</li>
<li id="caption1">caption 1</li>
<li id="caption2">caption 2</li>
<li id="caption3">caption 3</li>
<li id="caption4">caption 4</li>
<li id="caption5">caption 5</li>
</ul>
</div>
You can use Array.from().
Array.from(nodeList)
First of all I want to thank #Red Mercury that his answer greatly boosted my knowledge in JavaScript. I am new to Stack Overflow and don't know how to mark his answer green, if there is a gold mark, I would do for him. Thank you Red Mercury.
What I was trying to do is to put captions list as a sliding captions. It was easy to do with arrays in Javascript, but I was unable to convert node list into array, because nodelist did not work in loops with innerHtml. So here is the solution:
<html>
<head>
<title>Slide 3</title>
<style>
.captn {
padding-top: 550px;
text-align:center;
font-family:serif, fantasy;
font-size:36px;
color: #009933;
text-decoration: none;
text-transform: uppercase;
}
</style>
</head>
<body>
<div>
<ul id = "caption" class="captn">
<li id = "caption0">caption 0</li>
<li id = "caption1">caption 1</li>
<li id = "caption2">caption 2</li>
<li id = "caption3">caption 3</li>
<li id = "caption4">caption 4</li>
<li id = "caption5">caption 5</li>
<li id = "atim">item</li>
<li id = "caption6">caption 6</li>
</ul>
</div>
<script>
var i = 0;
var j = 0;
var intv = 1000;
var msg = "";
var cap = [];
var capList = "";
var captions = Array.from(
document.querySelectorAll('.captn [id ^= "caption"]')
);
var captionsText = captions.map(function(caption) {
return caption.textContent;
})
for (i = 0; i < captions.length; i++) {
cap[i] = captionsText[i] + "<br>";
msg = cap[i];
capList += msg.replace(/\,/g, "");
}
b = captions.length;
function swapImage() {
var elm = document.getElementById("caption");
elm.innerHTML = cap[j];
if(j < b - 1 ) {
j++;
}
else {
j = 0;
}
setTimeout("swapImage()", intv);
}
window.onload=swapImage;
</script>
</body>
</html>

How to add and delete object in javascript?

I have order list in HTML :
<ol id="myList">
<li>Tea</li>
<li>Milk</li>
<li>Water</li>
</ol>
<button onclick="myFunction()">Try it</button>
And Ii write code in Javascript, and now I can add one item in this list. I have also set up limit of adding items. When I add one items, then how can I delete it?
<script>
var limit = 1
var currentAmount = 0;
function myFunction() {
//Check we haven't reached our limit.
if(currentAmount < limit){
var x = document.createElement("li");
var t = document.createTextNode("Coffee");
x.appendChild(t);
document.getElementById("myList").appendChild(x);
currentAmount++; //Increment our count
}
}
</script>
You could add remove button to every item in the list and attach onclick event to it that will call removeItem() function, check example below.
Hope this helps.
Snippet
var limit = 1
var currentAmount = 0;
function myFunction() {
//Check we haven't reached our limit.
if(currentAmount < limit){
var x = document.createElement("li");
var remove_btn = document.createElement("input");
remove_btn.setAttribute("type", "button");
remove_btn.setAttribute("value", "X");
remove_btn.setAttribute("onclick", "removeItem(this)");
x.appendChild(remove_btn);
var t = document.createTextNode("Coffee");
x.appendChild(t);
document.getElementById("myList").appendChild(x);
currentAmount++; //Increment our count
}
}
function removeItem() {
event.target.parentNode.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="myList">
<li><button onclick="removeItem(this)">X</button> Tea</li>
<li><button onclick="removeItem(this)">X</button> Milk</li>
<li><button onclick="removeItem(this)">X</button> Water</li>
</ol>
<button onclick="myFunction()">Try it</button>
Well, it depends which element you want to remove, but for example, to remove the last element, add this button:
<button onClick="removeItem();">Now try this</button>
and this script:
function removeItem() {
document.getElementById("myList").lastChild.remove();
}
Got carried away, it removes items as OP requested and it:
Generates the delete button for every list item.
Added delete buttons for the old list items.
Added a text input so the user can input the list items.
Added an eventListener to the list in order to handle which button was clicked and save memory having one eventListener instead of one for each button.
Snippet
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Shopping List</title>
<style>
#inp1 {
margin: 10px 15px;
width: 25ex;
}
.item {
max-width: 30ex;
position: relative;
}
.del {
line-height: 1;
width: 7ex;
margin: 0 20px;
padding: 0 3px;
position: absolute;
right: -10px;
}
.del:before {
content: 'Delete';
font: inherit;
}
</style>
</head>
<body>
<h2>Shopping List</h2>
<ol id="list">
<li class="item">Tea
<button class="del"></button>
</li>
<li class="item">Milk
<button class="del"></button>
</li>
<li class="item">Water
<button class="del"></button>
</li>
</ol>
<input id="inp1" name="inp1" placeholder="Grocery Item" />
<button onclick="list(inp1.value)">Add</button>
<script>
var limit = 6
var currentAmount = 3;
var ol = document.getElementById("list");
function list(item) {
//Check we haven't reached our limit.
if (currentAmount < limit) {
var li = document.createElement("li");
var str = document.createTextNode(item);
var btn = document.createElement('button');
li.appendChild(str);
li.appendChild(btn);
li.classList.add('item');
btn.classList.add('del');
ol.appendChild(li);
currentAmount++; //Increment our count
}
return false;
}
ol.addEventListener('click', function(event) {
if (event.target != event.curentTarget) {
var tgt = event.target;
var li = tgt.parentElement;
ol.removeChild(li);
currentAmount--;
}
event.stopPropagation();
}, false);
</script>
</body>
</html>

how to use addEventListener to get list of elements?

Can someone help out here? i have this project going on... i want that when the list items in the 'players' array are clicked, they should move to the 'actual-players' list. i want to use an event listener.... below are my codes...
JAVASCRIPT
function init(){
var players = ["Player1", "Player2", "Player3", "Player4",
"Player5"];
var listItems = document.getElementById("first");
for (var i = 0; i < players.length; i++){
var newPlayersList = document.createElement("li");
newPlayersList.ClassName = "list-item";
var listItemsValue = document.createTextNode(players[i]);
newPlayersList.appendChild(listItemsValue);
listItems.appendChild(newPlayersList);
}
//Below is where i write the codes to set the elements of the 'players' array to move to the 'actual-players' list. But it doesn't work!
var players = document.getElementsByClassName("list-item");
for(var i=0; i<players.length; i++){
players[i].addEventListener("click", function(){
var text = this.innerHTML;
var liElement = document.createElement("li");
liElement.ClassName = "test";
var text = document.createTextNode(text);
liElement.appendChild(text);
var lis = document.getElementById("actual-
players").getElementsByTagName("li");
if (lis.length == 4){
alert("Don't let more than four players");
} else {
document.getElementById("actual-
players").appendChild(liElement);
this.remove();
}
});
}
}
window.onload = function(){
init();
};
HTML
<html>
<head>
<title>Table Soccer Teams</title>
<link rel="stylesheet" type="text/css" href="soccer.css" />
<script type="text/javascript" src="table_soccer.js" ></script>
</head>
<body>
<a id="reset" href="javascript:location.reload(true)"
class="btn">Reset</a>
<div id="soccer_field">
<div class="players" onsubmit="return(validateForm ());">
<h2>Possible Players</h2>
<ul id="first"></ul>
<p class="one">Click on names above <br>to select actual
players</p>
</div>
<div class="actual_players">
<h3>Actual Players</h3>
<ul id="actual-players" ></ul>
<p class="two">Click button below to <br>generate Teams</p>
<br>
<a id="generate" href ="#" class="btn">Click here</a>
</div>
</div>
</body>
</html>

Javascript FAQ drop down

Im trying to create a simple FAQ drop down but for some reason it is not working. Would you mind taking a look?
Thanks guys!
CSS
#faqs h3 { cursor:pointer; }
#faqs h3.active { color:#d74646; }
#faqs div { height:0; overflow:hidden; position:relative; }
#faqs div p { padding:0; margin-bottom:15px; }
JavaScript:
$(document).ready(function() {
$('#faqs h3').each(function() {
var tis = $(this),
state = false,
answer = tis.next('div')
.hide()
.css('height','auto')
.slideUp();
tis.click(function() {
state = !state;
answer.slideToggle(state);
tis.toggleClass('active',state);
});
});
});
HTML
<div id="faqs">
<h3>This is question 1?</h3>
<div>
<p>This is the answer to question #1.</p>
</div>
<h3>This is question 2?</h3>
<div>
<p>This is the answer to question #2.</p>
</div>
</div>
The functions below can be used for what you need:
HTML
<div id="QA">
<ul>
<li>Question 1</li>
<li>Answer 1</li>
<li>Question 2</li>
<li>Answer 2</li>
</ul>
<ul>
<li>Question 3</li>
<li>Answer 3</li>
<li>Question 4</li>
<li>Answer 4</li>
</ul>
</div>
JavaScript:
<script type="text/javascript">
function toggle(tag) {
var x=document.getElementsByName(tag)[0];
var a = x.parentNode
if (a.style.display=='block'){
a.style.display='none'
}else{
a.style.display='block'
}
}
function init() {
//this function will add show hide functionality to paired list items,
//as long as the answer is a list item straight after the question list item.
//You can also have as many separate lists as you want.
//all lists must be contained within a div with id QA
var obj = document.getElementById('QA');
var elements = obj.getElementsByTagName('li');
var index = 1
//add javascript to question elements
//you could also add styling to question elements here
for (var i=0; i < elements.length; i+=2){
var element = elements[i];
element.innerHTML = "<a href='javascript:toggle(" + index + ")'>" + element.innerHTML + "</a>"
index = index + 1
}
//add bookmark to answer elements and add styling
var index = 1
for (var i=1; i < elements.length; i+=2){
var element = elements[i];
element.innerHTML = "<a name='" + index + "' id='" + index + "'></a>" + element.innerHTML
index = index + 1
element.style.padding = '0px 0px 10px 20px' //add indent to answer
element.style.listStyleType = 'none' //remove bullet
element.style.display = 'none' //hide answer element
}
}
window.onload = init;
</script>

Categories