how to remove the child node in js - javascript

i have one parent node name orgdiv and one child node name newdiv. I am trying to remove the child node but its not working here is the code.
function ajxsrch(str) {
if (str.length != 0) {
if (count == 0) {
var newdiv = document.createElement('DIV');
newdiv.className = "newsearch";
var orgdiv = document.getElementById("search");
orgdiv.appendChild(newdiv);
count = 1;
alert("firstif");
} else alert("first if else");
} else {
alert(str);
count = 0;
alert(count);
newdiv.orgdiv.removeChild(newdiv);
}
}

There are a few issues with your approach, and your JavaScript console will typically assist in debugging most of these.
First of all, consider the objects newdiv and orgdiv. Inside your else block, you reference both of these, but they are not declared or initialized anywhere. There is a declaration in your if block, but of course that doesn't get run the second time this method is called. When the else block is executing, the if block is ignored altogether.
So you need to correct your object references:
function ajxsrch(str) {
var orgdiv = document.getElementById("search");
var newdiv = document.getElementById("newDivId"); // assuming div has an ID
...
Then of course, in your if block, you will initialize newdiv correctly since it doesn't exist yet.
newdiv = document.createElement('DIV');
newdiv.id = "newDivId";
newdiv.className = "newsearch";
Finally, when removing the element, you're incorrectly referencing the parent as a property of the child (newdiv.orgdiv.removeChild(newdiv);). Instead, just access the parent directly:
orgdiv.removeChild(newdiv);
So your final solution becomes:
function ajxsrch(str) {
var orgdiv = document.getElementById("search");
var newdiv = document.getElementById("newDivId");
if (str.length != 0) {
if (count == 0) {
newdiv = document.createElement('DIV');
newdiv.id = "newDivId";
newdiv.className = "newsearch";
orgdiv.appendChild(newdiv);
count = 1;
alert("firstif");
} else alert("first if else");
} else {
alert(str);
count = 0;
alert(count);
orgdiv.removeChild(newdiv);
}
}
See also Node.removeChild MDN docs

Related

Updating value in for loop / Reseting a for loop?

I'm working on my first school project so I don't have much experience in doing such web applications, that's why I decided to ask here.
How can I update the value in the for loop syntax or reset it entirely, so it iterates again, like I just reloaded it? I have another function that I decided not to show, simply because it would be useless to. What it does in the end is increments the taskCount.length by one. This part technically works but problem is, the function I'm going to show you now, once iterated, will always keep the default taskCount.length value, once the page is loaded, it never changes there. Is there any way I can update it?
Here's an example: The function above makes taskCount.length = '5' but when the page started it was taskCount.length = 4, and when I do alert(taskCount.length) from the console, I get 5. But the for loop doesn't want to change.
for (var i = 0; i < taskCount.length; i++) {
document.getElementsByClassName('task')[i].addEventListener('click', ((j) => {
return function() {
var shadow = document.createElement('div');
// Styling
var changingWindow = document.createElement('div');
// Styling
var changingTitle = document.createElement('p');
// Styling
var changingText = document.createElement('p');
// Styling
var changingTitleNode = document.createTextNode('Промяна');
var changingTextNode = document.createTextNode('Моля, изберете действие.');
var deleteTask = document.createElement('button');
var goUp = document.createElement('button');
var goDown = document.createElement('button');
var unchange = document.createElement('button');
// Styling
var deleteElementNode = document.createTextNode('Премахни задачата');
var goUpNode = document.createTextNode('Премести нагоре');
var goDownNode = document.createTextNode('Премести надолу');
var unchangeNode = document.createTextNode('Отказ');
var justBreak = document.createElement('br');
var justBreakAgain = document.createElement('br');
var justBreakOneMoreTime = document.createElement('br');
body.appendChild(shadow);
shadow.appendChild(changingWindow);
changingWindow.appendChild(changingTitle);
changingTitle.appendChild(changingTitleNode);
changingWindow.appendChild(changingText);
changingText.appendChild(changingTextNode);
changingWindow.appendChild(deleteTask);
deleteTask.appendChild(deleteElementNode);
deleteTask.onclick = function() {
document.getElementsByClassName('task')[j].parentNode.removeChild(document.getElementsByClassName('task')[j]);
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreak);
changingWindow.appendChild(goUp);
goUp.appendChild(goUpNode);
goUp.onclick = function() {
if (j !== 0) {
var saveThisTaskValue = document.getElementsByClassName('task')[j].innerHTML;
var savePreviousTaskValue = document.getElementsByClassName('task')[j - 1].innerHTML;
document.getElementsByClassName('task')[j].innerHTML = savePreviousTaskValue;
document.getElementsByClassName('task')[j - 1].innerHTML = saveThisTaskValue;
}
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreakAgain);
changingWindow.appendChild(goDown);
goDown.appendChild(goDownNode);
goDown.onclick = function() {
if (j !== document.getElementsByClassName('task').length - 1) {
var saveThisTaskValue = document.getElementsByClassName('task')[j].innerHTML;
var saveNextTaskValue = document.getElementsByClassName('task')[j + 1].innerHTML;
document.getElementsByClassName('task')[j].innerHTML = saveNextTaskValue;
document.getElementsByClassName('task')[j + 1].innerHTML = saveThisTaskValue;
}
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreakOneMoreTime);
changingWindow.appendChild(unchange);
unchange.appendChild(unchangeNode);
unchange.onclick = function() {
shadow.parentNode.removeChild(shadow);
}
}
})(i))
}
As a matter of the page reloading, you can always save the value as a cookie and reuse it again and again. You can update it whenever you want.
I don't fully understand you question, but maybe some recursion is what you need. Something along the lines of:
loop(5);
function loop(xTimes) {
for (var i = 0; i < xTimes; i++) {
if (newXTimes !== xTimes) {
loop(newXtimes);
break;
}
}
}
Maybe set newxTimes as a global variable that can be accessed inside loop.
In case someone "from the future" reads this question and it doesn't have any answers, I came up with the solution to reload the page everytime you change the value. Still, I'd like to do it without reloading.

Adding more classes to a javascript function

I'm trying to make a function run several div's in a Q&A accordion, but I can't figure out the right syntax for it to happen. In line 6, the classname 'questionV1' does the job well, but I want the function to run classnames 'questionV2' and 'questionV3' as well. I have tried to add questionV2 + V3, in the same line like this (divs[no].classname=='questionV1, questionV2, questionV3') but it does not work. The javascript looks like this:
function initShowHideDivs()
{
var divs = document.getElementsByTagName('DIV');
var divCounter = 1;
for(var no=0;no<divs.length;no++){
if(divs[no].className=='questionV1'){
divs[no].onclick = showHideContent;
divs[no].id = 'dhtmlgoodies_q'+divCounter;
var answer = divs[no].nextSibling;
while(answer && answer.tagName!='DIV'){
answer = answer.nextSibling;
}
answer.id = 'dhtmlgoodies_a'+divCounter;
contentDiv = answer.getElementsByTagName('DIV')[0];
contentDiv.style.top = 0 - contentDiv.offsetHeight + 'px';
contentDiv.className='answer_content';
contentDiv.id = 'dhtmlgoodies_ac' + divCounter;
answer.style.display='none';
answer.style.height='1px';
divCounter++;
}
}
}
window.onload = initShowHideDivs;
Here are two solution for your problem. One with regex, the other with string comparison.
RegEx Solution:
for(var index in divs){
var div = divs[index];
if(/questionV[123]/.test(div.className)) {
// code here
}
}
String comparison:
for(var index in divs){
var div = divs[index];
if(div.className === 'questionV1'
|| div.className === 'questionV2'
|| div.className === 'questionV3') {
// code here
}
}
also a link to jsfiddle

Uncaught TypeError: Cannot set property 'onfocus' of null

I am trying to learn JavaScript and I'm building this basic tutorial. In trying to demonstrate onfocus and onblur, I get this error message in my JavaScript console: Uncaught TypeError: cannot set property 'onfocus' of null.
Here is my code. I am new to learning JavaScript and could really use some help.
//alert("Hello, world!");
// this is a JavaScript alert button
//
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro to JavaScript! YAY!");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers(); // This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White-Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage, 5000);
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
If it's giving you that error, then it means that document.getElementById("email") evaluates to null, which means that no element exists with the id email.
That's all I can tell you without seeing the HTML that this JS is connected to.

Javascript clientHeight returns NaN in certain contexts

Interesting issue arising for me.
I am working on an infinite scroll thing in javascript that requires getting clientHeight of a div at some point:
here is the code:
document.addEventListener('DOMContentLoaded', init, false);
function init(){
var j = 0;
var inner1 = document.getElementById("innerDiv1");
inner1.addEventListener("scroll", function(event){ window.j = 2; checkForLoad();});
var inner2 = document.getElementById("innerDiv2");
inner2.addEventListener("scroll", function(event){ window.j = 1; checkForLoad();});
}
var i = 0;
var checkForLoad = function() {
var bottomDiv;
var bottomDivChild;
var offsetOfDiv;
var offsetOfPage;
if(window.j === 2){
bottomDiv = document.getElementById("innerDiv1");
bottomDivChild = bottomDiv.lastElementChild;
offsetOfDiv = bottomDivChild.offsetTop + bottomDivChild.clientHeight; //WORKS FINE
offsetOfPage = (document.getElementById("innerDiv1").pageYOffset) + (document.getElementById("innerDiv1").clientHeight); //THIS IS WHERE THE ISSUE IS
}
else if(window.j === 1){
bottomDiv = document.querySelector("innerDiv2 > div:last-child");
offsetOfDiv = bottomDiv.offsetTop + bottomDiv.clientHeight;
offsetOfPage = inner1.pageYOffset + inner1.innerHeight;
}
if(offsetOfPage > offsetOfDiv - 10) {
alert("time to add");
//eventually will be AJAX with XSL
if (i % 5 !== 0) {
i++;
alert("into the append part");
var newResults = document.createElement("div");
newDiv.innerHtml = "testing " + i;
if(window.j === 2){
document.getElementById("innerDiv1").appendChild(newResults);
}
else if(window.j === 1){
document.getElementById("innerDiv2").appendChild(newResults);
}
checkForLoad();
} else if (i%5 === 0) {
newDiv = document.createElement("div");
newDiv.innerHTML = "Show more Results! " + i;
document.getElementById("scrollingDiv").appendChild(newDiv);
newDiv.setAttribute("ID", "showResults");
newDiv.setAttribute("onClick", "showMore()");
}
}
};
I realize that there are some inconsistencies here, but they are in parts of the script i am not using. Here is the issue though, in the if(window.j === 2) statement, you can see that I use client height in a couple places. In the first one, it returns a number perfectly and life goes on as planned, but when I use it in the line where I get the "offSerOfPage", the sum becomes NaN. I am using firebug to debug it and when I add document.getElementById("innerDiv1").clientHeight to the watch list, it shows that it has a number attatched to it. Yet the sum is returned as NaN. I think my wording is a bit confusing here so if you need clarification, please ask! Thanks!

Passing a javascript value

I want to pass a numeric value through to the following Javascript function.
function swap2() {
var oldDiv = document.getElementById("product-grid");
var newDiv = document.getElementById("product-page");
oldDiv.style.display = "none";
newDiv.style.display = "block";
}
I want to be able to call the function with a number in the bracket like...
onclick="swap2(2)"
And then have the newDiv variable change based on that number like so...
var newDiv = document.getElementById("product-page2");
How can I go about doing this?
function(variable){
// process using 'variable'
}
that's how you pass a variable to a function. Thus:
function swap2(n) {
var oldDiv = document.getElementById("product-grid");
var newDiv = document.getElementById("product-page" + n);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}

Categories

Resources