ParentNode returns the false value - javascript

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
};

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.

Javascript :delete a parent element

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();

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();
}

Appending Paragraph at specific location

I need to be able to change a string of text to heading1 and do some additional formatting later on. Caught up on this part for now. Here is my sample code as of right now.
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var selection = DocumentApp.getActiveDocument().getSelection();
var body = DocumentApp.getActiveDocument().getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
var pocketelement = selectedElement.getElement().getText();
body.appendParagraph(pocketelement).setHeading(DocumentApp.ParagraphHeading.HEADING1);
}
I need it to delete the original string and append the paragraph at the original strings location. Not sure how to do that. any help will be appreciated!
The body.appendParagraph() method appends the given paragraph, like javascript, to the body, at the end of it.
You are looking for the .insertParagraph(index, Paragraph). To get the index, try body.getChildIndex(paragraph). See the code below.
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
var body = doc.getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
//holds the paragraph
var paragraph = selectedElement.getElement();
//get the index of the paragraph in the body
var paragraphIndex = body.getChildIndex(paragraph);
//remove the paragraph from the document
//to use the insertParagraph() method the paragraph to be inserted must be detached from the doc
paragraph.removeFromParent();
body.insertParagraph(paragraphIndex, paragraph).setHeading(DocumentApp.ParagraphHeading.HEADING1);
};

javascript selected value

I have created function for creating a div, when u selet the value in dropdown box , based upon the length the number of divs will be created , so the code is
<select onchange="test()" id="selected_opt">
<option value="0" selected>-Select-</option>
<option value="1">Communication</option>
<option value="2">XXXXXXXXXXXXX</option>
</select>
the function test is
function test(){
var result = get_id.options[get_id.selectedIndex].value;
if(result == 1){
var i = 0,
c = model_details_json.communication,
j = c.length,
communications_div = document.getElementById("model_communication");
if(j == 0){
alert('nothing');
}
for (; i<j; i++){
var communication = c[i];
var create_div = document.createElement('div');
create_div.id = 'communication_id'+i;
create_div.name = 'communication';
var create_anchor = document.createElement('a');
create_anchor.innerHTML = communication.communication_name;
communications_div.appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
create_anchor.setAttribute("href", "javascript:void(0);");
create_anchor.setAttribute("onclick","sample('"+communication.communication_name+"','"+create_div.name+"')");
}
}
for example the length is 6 means the six number of divs will be created , so what the problem is when i again click on communication in select dropdown i.e already the six divs have been created , when do it again then agin six divs are created , so totally 12 divs created when u do it again it goes for 6 multiples.......
so what i need is the number of div would not be repeated. and it should be validate whether the user is clicking the same value in dropdown
Check this to remove div elements considering your parent div model_communication.
You need to implement logic by checking if the div exist and stop the loop when you get a message like 'Div is already removed' as shown in the example.
In order to do so create div elements along with id
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
You need to remove all divs before create the new ones. Try adding a class name to it:
var create_div = document.createElement('div');
create_div.className = 'communication_div';
...
Now you can select the divs. Before the for statement add these lines to remove the divs with 'communication_div' class name:
var divs = document.getElementsByClassName('communication_div');
for(var i=0; i<divs.length; i++) {
divs[i].parentNode.removeChild(divs[i]);
}
Every script run will generate new divs and remove old ones.
use js map object to put selected value or length as key into the map then everytime user clicks a value, first check for its existence in the map. If not found in the map, that would mean length is not repeating and divs will be created.
something like:
var selectedValues = new Array();
.......
var result = get_id.options[get_id.selectedIndex].value;
if(selectedValues["val_"+result]) {
return;
}
selectedValues["val_"+result] = true;
you can check if the div is already created or present on page using getElementById('elementId') before creating it.
like in you code
for (; i<j; i++){
if(! document.getElementById('communication_id'+i)){ // do if element is not present on page
var communication = c[i];
var create_div = document.createElement('div');
create_div.id = 'communication_id'+i;
create_div.name = 'communication';
var create_anchor = document.createElement('a');
create_anchor.innerHTML = communication.communication_name;
communications_div.appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
create_anchor.setAttribute("href", "javascript:void(0);");
create_anchor.setAttribute("onclick",
"sample('"+communication.communication_name+"','"+create_div.name+"')");
}
}
Use replaceChild() instead of appendChild() on the Element object.

Categories

Resources