I can't understand why I am getting this error:
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Here is my code:
//create new div element, append it to the body, give it an ID and a Class.
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
console.log(container_clause_1);
//returns <div id="container_clause_1" class="cc1></div>"
const cClause1 = document.getElementById("container_clause_1");
console.log(cClause1);
//returns <div id="container_clause_1" class="cc1></div>"
const right_clause_1 = document.createElement("div");
console.log(right_clause_1); //returns <div></div>
document.cClause1.appendChild(right_clause_1); //Error occurs here!
I don't understand what is undefined in this situation. cClause1 is define. right_clause_1 is also defined. Granted, it's an empty div at this point, but that is what I am trying to do - add the div and then I can add the class and id, etc.
Also, I don't see any typos.
Also, if I replace document.cClause1.appendChild(right_clause_1);
with document.body.appendChild(right_clause_1); it works fine. Except that I don't want it inside the body, but rather, inside the container_clause_1 div.
I can't use JQuery for this. "Why not" is not really germane to the question. I have my reasons. Just understand that I can't use JQuery.
Well that was so obvious - after everyone started pointing out what I did wrong! Thanks for the answers!
Just another thing that this pointed out to me:
I can eliminate the variable cClause and just use container_clause_1
so my code is shorter!
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
const right_clause_1 = document.createElement("div");
container_clause_1.appendChild(right_clause_1);
right_clause_1.setAttribute("id", "right_clause_1");
right_clause_1.classList.add("r1");
Why have "document." in this line?
document.cClause1.appendChild(right_clause_1);
Surely you only need:
cClause1.appendChild(right_clause_1);
Related
Hello i was learning Javascript from 10 day of javascript videos and in last day it still runs error: Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
could someone help me
let ourForm = document.getElementById('ourForm')
let ourField = document.getElementById('ourField')
let ourList = document.getElementById('ourList')
ourForm.addEventListener('submit', (e) => {
e.preventDefault()
createItem(ourField.value)
})
function createItem(x) {
ourList.insertAdjacentHTML('beforeend', x)
}
This will be because the element with an id of ourList does not exist. Double check you have an element in your HTML with this id.
Please recheck your HTML code. It looks like you missed the id ourList somewhere. The error means that your javascript was unable to find the element with the given id.
If you check your HTML code, there must be an element with an id of "ourList" for your code to work. Since the error says that an object with that id currently returns a null, something is incorrect. You most likely either misspelled it, or forgot to add the id to the corresponding HTML element.
You do this by writing:
<ul id="ourList"> ... </ul>
where ul is your element type. (ul, ol, div...)
I am working on a javascript code where I can clone an element, but also want to delete one on click. Cloning works, but I can't remove one.
I have the following elements.
<input list="accountsdeb" name="deblist[1]" id="deblist" autocomplete="off">
<input list="accountsdeb" name="deblist[2]" id="deblist" autocomplete="off">
And now I want to remove the last one on click (last = highest number).
function remove1() {
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
var elem = document.getElementsByName("deblist["+dbla+"]");
alert(dbla);
//var last = debelelast - 1;
elem.parentNode.removeChild(elem);
}
As an orientation I used to have a look on an example from W3S and Stack. I have also seen that this works:
var elem = document.getElementById("myDiv");
elem.parentNode.removeChild(elem);
But this is random and as you can see I have tried to include this in my code.
The error I get is:
Uncaught TypeError: Cannot read property 'removeChild' of undefined
at HTMLAnchorElement.remove1 (index.php:179)
Where's the problem in my code, where is my thinking wrong?
I see two issues in the piece of code you provided,
deblist is used as id for 2 elements which is not advisable and due to this document.querySelectorAll('#deblist').length returns 2 (I am not sure if you intending to do so)
document.getElementsByName() (check here) will return a NodeList which needs to be iterated in order to access any of the returned elements. So here you need to select the child element by giving its index. In your case elem will have one element for the matched name deblist[2] and hence you need to access it like elem[0] for selecting its parent and deleting its child.
So the updated the code would be,
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
// console.log('dbla', dbla);
var elem = document.getElementsByName("deblist["+dbla+"]");
// console.log('elem 0', elem[0]);
// console.log('elem parentNode', elem[0].parentNode);
//var last = debelelast - 1;
elem[0].parentNode.removeChild(elem[0]);
Check the fiddle here
If the inputs are part of a group they could share a name property or such, and the use of jQuery could help you do something like...
$("input[name='group1']").last().parent().remove()
Or if not part of a group then just....
$("input").last().parent().remove()
I am learning JavaScript objects and have set myself a little project to create a slider. Its worth noting I coming from a jQuery background so my problem may lie with the way I trying to select the elements. I have the following HTML:
<div class="slider-viewport" id="mySlider">
<div class="slides-container">
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
</div>
</div>
and the following JavaScript:
(function(window, document, undefined){
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
var slider = {
sliderViewport: document.getElementById('mySlider'),
slidesContainer: document.querySelectorAll(this.sliderViewport + ' .slides-container')
};
console.dir(slider.sliderViewport + ' .slides-container');
console.dir(slider.slidesContainer);
//Just testing to see if I can do something
slider.slidesContainer.style.color = 'blue';
}
})(window, document, undefined);
When I view Chrome Dev Tools I get the following:
[object HTMLDivElement] .slides-container
objects.js:16 NodeList[0]
objects.js:18 Uncaught TypeError: Cannot set property 'color' of undefined
The first console.dir seems to return the element I am after. I'm not sure what the second console.dir is returning and also why I get an error of undefined. Please can you give me a steer on where I am going wrong?
Many thanks in advance.
querySelectorAll() expects a string as parameter to evaluate as a CSS selector. You can't concat a HtmlDivElement with a string, this is your first problem. The second one is that the querySelectorAll() returns a NodeList as you can see on the console. The problem is that the list is empty.
You may want to try this:
var slider = {
sliderViewport: document.getElementById('mySlider')
}
slider.slidesContainer: slider.sliderViewport.querySelectorAll('.slides-container');
I didn't tested it, but it should works as described here.
querySelectorAll and querySelector gets a string parameter (css selector):
var slider = {
sliderViewport: document.querySelector('#mySlider'),
slidesContainer: document.querySelector('#mySlider .slides-container')
};
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am having an issue making a div a child of another div. I would like to learn how to do this in javascript.
I would like to essentially create this:
<body>
<div id = "graph">
<div id "data">
</div>
</div>
</body>
By using javascript. The end goal is to create many of these over and over again.
Here is the code I have so far:
var graph = document.createElement('div');
graph.id = "graph";
document.body.appendChild(graph);
var barWrapper = document.createElement('div');
barWrapper.id = "data";
The above works with no error. When I add:
document.getElementbyId("graph").appendChild("data");
I get "Uncaught Type Error: Undefined is not a function".
From my research this seems to be everyone's suggestion. Also, the appendChild function seems to be complete to my knowledge. What am I missing? Thank you in advance!!
Your problem (which is causing your type error) is you're attempting to append a string, not a reference to the child element itself.
var parent = document.createElement("div");
parent.id = "graph";
var child = document.createElement("div");
child.id = "data";
parent.appendChild(child);
You should be appending an object just like you were doing with body.
var parent = document.getElementById("graph");
parent.appendChild(barWrapper);
Edit:
You also dont need to call getElementById here. You should be able to append the child to parent then append the parent to body. Like this:
var graph = document.createElement('div');
graph.id = "graph";
var barWrapper = document.createElement('div');
barWrapper.id = "data";
graph.appendChild(barWrapper);
document.body.appendChild(graph);
The error is beign caused by the typo, it should be getElementById
document.getElementbyId("graph")
>TypeError: undefined is not a function
when you fix that and execute the code you will get
document.getElementById("graph").appendChild("data")
>NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
this is because you are trying to append a string and not an actual html node. you will need to grab the element first as well
document.getElementById("graph").appendChild(document.getElementById("data"));
Since you already have references to both these objects a cleaner solution would be
grap.appendChild(barWrapper);
There are a couple problems
document.getElementbyId("graph") should be document.getElementById("graph")
.appendChild("data") should be .appendChild(bargraph)
This JS works:
var graph = document.createElement('div');
graph.id = "graph";
document.body.appendChild(graph);
var barWrapper = document.createElement('div');
barWrapper.id = "data";
document.getElementById("graph").appendChild(barWrapper);
Fiddle here: http://jsfiddle.net/hatvjete/
I am trying to get a div that is inside another div, since the id of the second div is variable, i use
var wrappingdiv = document.getElementById('divId')
to get the wrapping div then
var insidediv = wrappingdiv.getElementsByTagName('div')
but i get the getElementsByTagName is not a function error, i guess the syntax is wrong, could you guys put me in the right direction?
Thanks in advance.
Edit : I will correct myself, I am trying to get the body of a gmail email, so :
var element = content.document.getElementsByClassName("ii gt m13fbe3a51e95e196 adP adO");
it returns an object xraywrapper[object htmlcollection]
Edit 2 :
I am using mozilla firefox, and i am developing my own extension, to access source code of Google mail i use simple javascript (content.document...)
If you doesn't have any element with the id divId then wrappingdiv will be equal null:
And when trying to get null.getElementsByTagName you will get a type error:
TypeError: Cannot read property 'getElementsByTagName' of null
In
var element = content.document.getElementsByClassName(
"ii gt m13fbe3a51e95e196 adP adO");
getElements <- the s means this returns multiple elements (in a list-like collection), not just one element.
You might just want to pick out the first one it found.
var element = content.document.getElementsByClassName(
"ii gt m13fbe3a51e95e196 adP adO")[0];
There is also a small risk that it might not be m13fbe3a51e95e196 on every page, or forever. So perhaps you should generalise your search a bit. How about just searching for class "adP"?
The syntax isn't wrong. document.getElementById('divId') probably just fails to match the id of any existing element, so it returns null (which doesn't have a getElementsByTagName method).
DEMO
var wrappingdiv = document.getElementById("divId");
var insidediv = wrappingdiv.getElementsByTagName('div');
var i = 0;
for(i=0;i<insidediv.length;i++)
alert(insidediv[i].innerHTML);