Javascript :delete a parent element - javascript

How can I delete the parent element of a child using an event listener.
I have an html form that when submitted, runs the makeNewBook function and pushes an object containing the form information to an array called myLibrary. It then creates a container div that displays the info from that form, which is placed in a predefined div called shelf(bookshelf). That container also has a delete button in it.
The delete button has an event listener that removes the object from the array, but how can I also remove the container from the page using that last event listener? Thanks
Javasctipt:
function makeNewBook() {
let x = new Book(bookInput.value, authorInput.value, pagesInput.value, readInput.value) //create a new book using the input vals
myLibrary.push(x) //push the new book object to the books array;
console.table(myLibrary)
let container = document.createElement('div') //create a container for all the info
container.setAttribute('class', 'container')
let titlePara = document.createElement('p')
titlePara.textContent += 'Title: ' + x.title;
let authorPara = document.createElement('p')
authorPara.textContent += 'Author: ' + x.author;
let pagesPara = document.createElement('p')
pagesPara.textContent += 'Pages: ' + x.pages;
let readPara = document.createElement('p')
readPara.textContent += 'Read: ' + x.read
// delete button
let deleteBtn = document.createElement('input');
deleteBtn.setAttribute('class','delete')
deleteBtn.type = 'submit';
deleteBtn.value = 'Delete'
// append everyhting to the container div to be put on the shelf
container.appendChild(titlePara)
container.appendChild(authorPara)
container.appendChild(pagesPara)
container.appendChild(readPara)
container.appendChild(deleteBtn)
container.setAttribute('class', `container ${x.title}`)
shelf.append(container)
deleteBtn.addEventListener('click',()=>{
let index= myLibrary.indexOf(x);
myLibrary.splice(index,1); //delete that object from the myLibrary array
document.body.remove(deleteBtn.parentElement) //This does not work
})
}

You have to call remove on the node itself
deleteBtn.parentElement.remove();

Related

The value of input is not being assigned to a div

I want to get the text from the text area (id= getText), and than assign its value to the new div that I have created but the value is not being saved inside that new div.. I have tried many times but the value of the input is not saved and there is not change in when I click the button
let getText = document.getElementById("getText"); // this is textarea
let select = document.getElementById("selectBtn"); //this is button
//this is another div
let result = document.getElementById("result");
let new_p = document.createElement("div"); //creating element
new_p.innerHTML = "";
result.appendChild(new_p); // adding into resut div
//getting inner text of the input
let value = new_p.innerText;
//adding an event listener
select.addEventListener("click", function(e) {
e.preventDefault();
new_p.innerHTML = value;
//it does not works and the value is not saved
})
let getText = document.getElementById("getText"); // this is textarea
let select = document.getElementById("selectBtn"); //this is button
//this is another div
let result = document.getElementById("result");
let new_p = document.createElement("div"); //creating element
new_p.innerHTML = getText.value;
result.appendChild(new_p); // adding into resut div
//getting inner text of the input
let value = new_p.innerText;
//adding an event listener
select.addEventListener("click", function(e) {
e.preventDefault();
new_p.innerHTML = getText.value;
console.log(value)
//it does not works and the value is not saved
})
Replace new_p.innerHTML = ""; for
new_p.innerHTML = getText.value
and inside of click event,
new_p.innerHTML = getText.value;
Moving forward, try to use online code editors,
to post your code, Since it might be easier for anyone to assist you, Be aware to remove any personal info from the code.
Here is a fiddle with your code https://jsfiddle.net/k8b24n3q/12/
The reason was not working, was because you were setting on click event an undefined value.

Creating favourites list - how to copy item from one list to another on click?

(New to Javascript)
I have created a input box which turns the input value into a list item, and adds a star
I am trying to create a new list whereby when the star is clicked on, it will copy into the 'favourites' section
I have tried this, but it is not working
let newStarSpan = document.querySelector("span")
newStarSpan.addEventListener('click', function(e){
//on click, get the parent node of the item clicked on
//i.e., want to return the individual <li> list item for the starSpan that was cliked on
let favNode = this.parentNode
//create a copy of this list item (the parent node)
let nodeCopy = favNode.cloneNode(true)
//add it to list B - favourites list
listB.appendChild(nodeCopy)
https://codepen.io/jemimacholzer/pen/dyYMKxj
You have few issues in your code, the first issue is related to the selector
const listB = document.querySelector('listB')
update it with
Fix:
const listB = document.getElementById('listB')
the other issue is related to newSpan event declaration & its scope, the newSpan can't be accessed outside of btn.onclick function.
You also assigned click listener to newSpan which seems to declare & bind on page when no newSpan is present in Dom. So instead of defining the listener you need create a function which triggers on newSpan click and bind that function during newSpan creation.
const listA = document.getElementById("listA")
const input = document.querySelector('input')
const btn = document.querySelector('button')
const listB = document.getElementById('listB')
btn.onclick = function() {
let Shopitem = input.value //store current value of input element in variable
input.value = ' ' //empty input element
const listItem = document.createElement('li') //creating a list item for the shopping item
listItem.setAttribute('id', Shopitem)
const span = document.createElement('span') //list text
const newBtn = document.createElement('button') //creating button to delete item
var starSpan = document.createElement("span")
var text = document.createTextNode("\u2B50")
starSpan.appendChild(text)
//making span and button children of the list item (containing within each list item)
listItem.appendChild(starSpan)
listItem.appendChild(span) //add list text to list item
listItem.appendChild(newBtn) //add list remove button to list item
newBtn.textContent = 'Delete'
span.textContent = Shopitem
listA.appendChild(listItem) //add li to the ul list
newBtn.onclick = function(e) {
list.removeChild(listItem)
}
starSpan.onclick = function(e) {
cloneListItem(listItem)
}
input.focus(); //focus the input method ready for entering the next shopping list item
}
//need to create new reference to star span as old reference is inside eother function
function cloneListItem(favNode){
//create a copy of this list item (the parent node)
let nodeCopy = favNode.cloneNode(true)
//add it to list B - favourites list
listB.appendChild(nodeCopy)
}
https://codepen.io/jemimacholzer/pen/dyYMKxj

ParentNode returns the false value

I have some troubles with ParentNode
See I'm Working on a WYSIWYG and I want to tell me what are the parents of selected text.
It works fine till I have two Texts with diffrent style
for example :
<b>Bold<b> NotBold
When I click on Bold it returns BODY tag and when I click on it again It retruns B tag.
and Same about NotBold When I click on NotBold after I clicked on Bold It returns B tag and when I click this again it returns me BODY
Where is the problem ?
document.addEventListener("DOMContentLoaded",iFrameStart,false); //make iFrame Editable
function iFrameStart() {
iframe.document.designMode="On";
}
let frame = document.getElementById('iframe');
frame.contentWindow.onselectstart=function()
{
let frame = document.getElementById("iframe");
let select=frame.contentWindow.getSelection(); //get the selected text
let a = select.focusNode.parentNode; //get the parent of selected text
//if it removed it returns the value in " "
let array= ['ok']; //create an array
while (a) {
array.push(a); //add to the array
a=a.parentNode;
}
console.log(array); //display the parents
};
Please try the following. it is getting the parent node fine. You are not closing the tag in your example
<iframe id='iframe'></iframe>
document.addEventListener("DOMContentLoaded", iFrameStart, false); //make iFrame Editable
function iFrameStart() {
window.iframe.document.designMode = "On";
}
let frame = document.getElementById("iframe");
frame.contentDocument.body.innerHTML = "<b>Bold </b> <c>not bold</c>";
//window.iframe.document.getElementByTag("body")[0].innerHTML = "SAQIB";
frame.contentWindow.onclick = function() {
let frame = document.getElementById("iframe");
let select = frame.contentWindow.getSelection(); //get the selected text
let a = select.focusNode.parentNode; //get the parent of selected text
console.log(select.focusNode.parentNode);
//if it removed it returns the value in " "
let array = ["ok"]; //create an array
while (a) {
array.push(a); //add to the array
a = a.parentNode;
}
console.log(array); //display the parents
};

Firebase, finding the key of parent based on child's value

essentially what I am trying to do is to create a button on a created text node in js. Then find the value of spmet and remove the question (spmet) from the database.
However I can't figure out how to properly reference it, and find the specific value that I want deleted. (so other picture, remove that question from database when I press the "x")
this is the the way to remove questions
This is the firebase layout
var btn = document.createElement("BUTTON");
var btnText = document.createTextNode("x"); //create button
btn.appendChild(btnText);
tekst.appendChild(btn);
btn.id = "questionBtn";
//bytter enter som gir linjeskift til <br>
tekst.innerHTML = tekst.innerHTML.replace(/\n/g, '<br>');
chat.appendChild(bubble);
setTimeout(function(){
chat.classList.add('visible')
}, 1);
chat.scrollTop = chat.scrollHeight;
console.log(bubble);
// Function to remove the question on the button generated
tekst.onclick = function removeQ(){
window.alert("Knapp funker");
var ref = database.ref();
ref.child('spm')
.orderByChild('spmet')
.equalTo(spmet)
.once('value', function(snap) {
//remove the specific spmet parent
window.alert(snap.val());
});
document.getElementById("cont1").removeChild(bubble); // removes text from page
var spmRef = ??
spmRef.remove(); //can't reference properly
}
When you generate the HTML element for each question, keep the ID of that question as an attribute on that HTML element:
ref.child("spm").on("child_added", function(snapshot) {
var div = document.createElement("div");
div.id = snapshot.key;
div.innerText = snapshot.child("spmet").val();
div.onclick = onSpmClick;
questionContainer.appendChild(div);
});
Now when the user clicks on one of the questions, you can get the key from that div and remove it:
function onSpmClick(e) {
var key = e.target.id;
ref.child("spm").child(key).remove();
}

Div-Element don't refresh after dynamic adding of elements

I'm working on an Ionic-app.
On one of my pages i'm adding elements dynamically to a div-element.
The elements are added but i can't see them on the page.
Just after clicking F5 and running the controller-code again i can see them.
Here's the code for adding the elements:
if ($scope.eigenschaften != null) {
//TODO Eigenschaften in Loop durchgehen und auf panel_dynamic Controls erzeugen
var panel_dynamic = document.getElementById('panel_dynamic');
if (panel_dynamic.hasChildNodes()) {
panel_dynamic.removeChild(panel_dynamic.childNodes[0]);
}
var content = document.createElement('div');
for (n = 0; n <= $scope.eigenschaften.length - 1; n++) {
// Creates a new div with controls
var line = document.createElement('div');
var para = document.createElement('p');
// Creates a div-row
var div_row = document.createElement('div');
div_row.setAttribute('class', 'row');
// Creates a div-col with label
var div_col_label = document.createElement('div');
div_col_label.setAttribute('class', 'col');
div_col_label.appendChild(CreateLabel('font-size:16px;font-weight:bold;', $scope.eigenschaften[n].name));
div_row.appendChild(div_col_label);
// Creates a div-col with control
var div_col_control = document.createElement('div');
div_col_control.setAttribute('class', 'col');
div_col_control.appendChild(CreateTextbox());
div_row.appendChild(div_col_control);
// Adds the div-row to the para
para.appendChild(div_row);
// Adds the new para to the line
line.appendChild(para);
// Adds the new line to the content
content.appendChild(line);
}
// Adds the content-div to panel_dynamic
panel_dynamic.appendChild(content);
}
"eigenschaften" is an array with the data.
It looks like you aren't triggering change detection. You should add the elements using an ng-repeat in your template that's bound to an array or some other iterable on the model instead. Then everytime you add something new to the iterable, it will get added in the view.
Unfortunately i used the id for my container-div "panel_dynamic" even in another template. And JavaScript was getting the other div by getElementById. Now i have changed the ids and it works.

Categories

Resources