I'm working on a simple blackjack game, where the dealer will be served one card and the player two (basic rules).
The cards display just fine, but when I append a class to the dealers card container, the container refuses to acknowledge the class I just appended. I copy and pasted the same code from my player function which deals the player cards successfully and that doesn't seem to work on my dealer function either.
The class I am trying to append is "symbol".
If you take a look at the jsfiddle snippet below, you can inspect it to see the class "symbol" doesn't get appended to dealer, but works completely fine in the player function.
Thank you in advance for the help.
http://jsfiddle.net/vorqdkb7/1/
Dealer
function deal_dealer_cards(){
let dealerContainer = document.querySelector('.dealer_container');
let card = deck.pop();
dealerHand.push(card);
let dealerCard = document.createElement('div');
dealerCard.className = "dealer_card";
dealerContainer.append(dealerCard);
let rank = document.createElement('div');
rank.className = "rank";
dealerCard.append(rank);
rank.innerHTML = card.value;
let symbol = document.createElement('div');
dealerCard.append(symbol);
symbol.className = 'symbol';
let cardSymbol = document.createElement('span');
symbol.append(cardSymbol);
cardSymbol.setAttribute('id', 'card_symbol');
let i = document.createElement('i');
cardSymbol.append(i);
let fa = "fas ";
Player
function deal_player_cards(){
let playerContainer = document.querySelector('.player_container');
let fa = "fas ";
for (let i = 0; i < 2; i++){
let card = deck.pop();
playerHand.push(card);
let playerCard = document.createElement('div');
playerCard.className = "player_card";
playerContainer.append(playerCard);
let rank = document.createElement('div');
rank.className = "rank";
playerCard.append(rank);
rank.innerHTML = card.value;
let symbol = document.createElement('div');
playerCard.append(symbol);
symbol.className = 'symbol';
let cardSymbol = document.createElement('span');
symbol.append(cardSymbol);
cardSymbol.setAttribute('id', 'card_symbol');
let i = document.createElement('i');
cardSymbol.append(i);
let fa = "fas "; }
Ok the div .symbol does get appended but down below in your code you update the className.
With this code
symbol.className = fa + "fa-heart";
Now I don't know exactly what you would need here. But if you want to append the symbol class maybe you want to do something like
symbol.className += " " + fa + "fa-heart";
I hope it helps
you can use symbol.classList.add('fa-heart') to add class to the element because you did is to override the whole className attribute with the new one.
and you can use symbol.classList.remove('fa-heart') to remove a specific class too.
Hope this helps you.
Related
Intro: I am using fetch method to get data from API. inside forloop i am not using the template string because somebody told me. it is not a good way to write HTML code inside template sting. So that's why i am using javascript DOM Element to render out the data from API. But i am new in JavaScript i want to know how can i write less code with DOM Element. the code below is too much and complicated. I have dropdown menu inside pending-sale div which contain a form attributes. Which I haven't written yet, if i write that dropdown menu code my code will be even more complicated as I write the code..
Needs: i just want to know how can i write my code less and understandable? Can anyone tell me if the code I am writing is correct? If this is not true, please guide me a little...
I would be grateful for any help.
main.js
const orderCard = document.querySelector('#pending-sales');
function pendingSaleBuild() {
orderCard.innerHTML = ''
fetch('/pending-sale-api/')
.then((res) => res.json())
.then((data) => {
data.map(item => {
// card title
const colLg = document.createElement('div')
colLg.classList.add('col-lg-12')
const hPanel = document.createElement('div')
hPanel.classList.add('hpanel')
hPanel.classList.add('hyellow')
const pBody = document.createElement('div')
pBody.classList.add('panel-body')
hPanel.appendChild(pBody)
colLg.appendChild(hPanel)
orderCard.appendChild(colLg)
const h5 = document.createElement('h5');
h5.classList.add('text-capitalize')
// card tilte link
const a = document.createElement('a');
h5.appendChild(a)
linkText = document.createTextNode(item.customers);
a.appendChild(linkText);
a.href = "#";
pBody.appendChild(h5);
// hr Element
const hr = document.createElement('hr');
pBody.appendChild(hr)
// row div
const rowDiv = document.createElement('div');
rowDiv.classList.add('row');
// project - label div
const colDiv = document.createElement('div');
colDiv.classList.add('col-sm-4');
rowDiv.appendChild(colDiv);
// project lable div
const proLable = document.createElement('div');
proLable.classList.add('project-label');
proLable.innerText = 'Saler Name';
colDiv.appendChild(proLable);
// small text Element
const smallEle1 = document.createElement('small')
smallEle1.innerText = item.saler
colDiv.appendChild(smallEle1);
const colDiv2 = document.createElement('div');
colDiv2.classList.add('col-sm-4');
rowDiv.appendChild(colDiv2);
// project lable div
const proLable2 = document.createElement('div');
proLable2.classList.add('project-label');
proLable2.innerText = 'Timestamp';
colDiv2.appendChild(proLable2);
// small text Element
const smallEle2 = document.createElement('small')
smallEle2.innerText = 'item.created_on'
colDiv2.appendChild(smallEle2);
const colDiv3 = document.createElement('div');
colDiv3.classList.add('col-sm-4');
rowDiv.appendChild(colDiv3);
// project lable div
const proLable3 = document.createElement('div');
proLable3.classList.add('project-label');
proLable3.innerText = 'Total Price';
colDiv3.appendChild(proLable3);
// small text Element
const smallEle3 = document.createElement('small')
smallEle3.innerText = '$ 124547'
colDiv3.appendChild(smallEle3);
pBody.appendChild(rowDiv);
})
});
};
In the function below, I create cards that have a toggle button and remove button. However, when I try to access the buttons with a queryselector, I get null. Anyone know how to access elements that were created in a different file? I can provide the full files if needed.
function updateDisplay() {
for (i = 0; i < myLibrary.length; i++){
let div = document.createElement('div');
let title = document.createElement('h5');
let author = document.createElement('h5');
let pages = document.createElement('h5');
let isRead = document.createElement('h5');
let removeButton = document.createElement('button');
let toggleButton = document.createElement('button');
div.classList.add('card');
title.classList.add('title');
author.classList.add('author');
pages.classList.add('pages');
isRead.classList.add('isRead');
removeButton.classList.add('removeButton');
toggleButton.classList.add('toggleButton');
title.textContent = myLibrary[i].title;
author.textContent = myLibrary[i].author;
pages.textContent = `${myLibrary[i].pages} pages`;
isRead.textContent = myLibrary[i].isRead ? 'Read' : 'Unread';
removeButton.textContent = 'Remove';
toggleButton.textContent = 'Toggle Read Status';
Your problem is obvious you're creating the elements but not appending the into the body.
you'll have to append each element you create like the following example:
var element= document.createElement("div"); // Create a <div> element
element.innerHTML = "some content"; // Insert text
document.body.appendChild(element); // Append <div> to <body>
note that you can do document.body.append(div,title,author,pages,isRead,removeButton,toggleButton);
to append them all in one line
Jsfiddle Here
const btnTodo = document.querySelector('.btnTodo');
const todoList = document.querySelector('.todoList');
const removeBtn = document.querySelector('.btnRemove');
btnTodo.addEventListener('click', () => {
var todoText = txtTodo.value.trim();
var listItem = document.createElement('p');
listItem.innerHTML = todoText + ' <button class="btn btnRemove"><i class="big fas fa-trash"></i></button>' + '<br>';
todoList.append(listItem);
txtTodo.innerText = null;
});
removeBtn.addEventListener('click', () => {
//WHAT TO DO??
});
I am in high school. I wanted to include a remove functionality to my todo app. I made this by the knowledge given to me by my school.
Okay so there are various ways of doing this, here's one of the ways:
let txtTodo = document.querySelector('.txtTodo');
let btnTodo = document.querySelector('.btnTodo');
let todoList = document.querySelector('.todoList');
btnTodo.addEventListener('click', () => {
let todoText = txtTodo.value.trim();
let listItem = document.createElement('p');
listItem.innerHTML = todoText + ' <button class="btn btnRemove"><i class="big fas fa-trash"></i></button>' + '<br>';
todoList.append(listItem);
txtTodo.innerText = null;
listItem.querySelector('.btnRemove').addEventListener("click", () => {
listItem.remove()
});
});
Fiddle
One thing to keep in mind is that storing all remove buttons in a variable beforehand (as you attempted in line 3) isn't going to work because is isn't a live collection and thus when you append new buttons in the DOM then the stored collection would become stale. Hence it's a good idea to add event listeners to newly appended elements as I did above.
Also you should be doing txtTodo.value = ""; instead of txtTodo.innerText = null; to clear the input.
Good luck!
I am trying to append newly created elements to a div, then append the div to a document fragment, but it isn't working as expected. Please help me identify what I am missing.
//array of values to look up
let channels = ["channel1", "channel2", "channel3","channel4","channel5","channel6","channel7","channel8","channel9","channel10","channel11","channel12","channel13","channel14","channel15","channel16"];
//jsonp request function defined
function streamRequest () {
//identify DOM elements for final appendChild
let docFrag = document.createDocumentFragment();
let container = document.getElementById("main-container");
//create container and elements for the acquired information
let div = document.createElement("div");
let image = document.createElement("img");
let p = document.createElement("p");
let p1 = document.createElement("p");
let p2 = document.createElement("p");
//variables for request responses
let logo;
let name;
let status;
let game;
channels.forEach(function channelsRequest(channel){
$.getJSON("https://api.twitch.tv/kraken/streams/" + channel + "?callback=?", function callback(data) {
if(data.stream === null){
status = "Offline"
game = "Offline"
} else if (data.stream != null) {
status = "Online"
game = data.stream.game
}
console.log(channel, status, game);
$.getJSON("https://api.twitch.tv/kraken/channels/" + channel + "?callback=?",function logoRequest(data) {
name = data.display_name;
if(data.logo === null) {
logo = "http://www.logowik.com/uploads/images/379_twitch.jpg"
} else if (data.logo != null) {
logo = data.logo
}
//set attributes and inner HTML for new elements
image.setAttribute("src",logo);
image.setAttribute("alt","photo of channel's image");
image.className = "image";
p.innerHTML = name;
p.className = "name";
p1.innerHTML = status;
p1.className = "status";
p2.innerHTML = game;
p2.className = "game";
//append elements to the div
div.appendChild(image)
div.appendChild(p)
div.appendChild(p1)
if(status === "Online"){
div.appendChild(p2)
}
div.className = "tv-block";
docFrag.appendChild(div);
console.log(data, name, logo, docFrag);
});
});
});
//append final document fragment to the DOM
container.appendChild(docFrag);
};
`
From what I understand, you should be able to append everything to the a div, then append the div to the fragment. When I run the code, nothing is amended to the DOM. I think it may be because of scoping, or the second json request isn't set up properly
I know this answer comes a year later but as I've just completed the same challenge I thought it might make sense to share my solution as I also had the same problem. It looks like creating a new DOM element and appending all generated divs to it and then appending this element to an existing DOM element is faster than using document fragment. So my structure looks like this:
<body>
<main>
<header>
</header>
</main>
<footer>
</footer>
</body>
And then I append to the main a div#container created in js and containing all generated divs.
Here is a link to the completed project.
So I have created elements in my html using javascript. The only problem is that my button is not showing up. Following is my code:
var search_div1 = document.createElement("div");
search_div1.className = "input-group row-fluid";
var search_div2 = document.createElement("div");
search_div2.className = "span4 offset4";
var search_input = document.createElement("input");
search_input.className = "form-control offset8";
search_input.id = "searchText";
search_input.type = "text";
search_input.placeholder = "Search...";
search_input.style.width = "200px";
search_input.style.marginLeft = "550px";
var search_span = document.createElement("span");
search_span.className = "input-group-btn";
search_span.width = "50px";
var search_button = document.createElement("button");
search_button.type = "submit";
search_button.id = "search";
search_button.name = "search";
search_button.className = "btn btn-flat";
search_button.onclick = myFunction;
var search_icon = document.createElement("i");
search_icon.className = "fa fa-search";
search_button.appendChild(search_icon);
search_span.appendChild(search_button);
search_input.appendChild(search_span);
search_div2.appendChild(search_input);
search_div1.appendChild(search_div2);
Everything else is showing perfectly except for the search_button and I have created buttons like this that work perfectly. Can someone kindly assist me? Thanks in advance.
You're using .appendChild() incorrectly. For example, this line of code:
search_input.appendChild(search_span);
Is trying to make a <span> a child of an <input>. That is not legal HTML.
Remember x.appendChild(y) makes y a child of x in the DOM hierarchy.
We can't really advise what the exact right sequence of appending is because we don't know what HTML structure you're trying to end up with. If you show us what you want the DOM hierarchy to look like when you're done, we can help with the proper code to achieve that.