Why does this code throw an error in the console reading TypeError: pizzaBox.querySelector is not a function. (In 'pizzaBox.querySelector('h6')', 'pizzaBox.querySelector' is undefined)?
function addToppingsToAll (toppings)
{
var pizzaBoxHolder = document.getElementById("PizzaBoxHolder");
var PizzaBoxList = pizzaBoxHolder.childNodes;
for ( var i = 0 ; i < pizzaBoxList.length ; i++ )
{
var pizzaBox = pizzaBoxList[i];
toppingList = pizzaBox.querySelector('h6');
toppingList.textContent = "You have " + toppings " on your pizza";
}
}
There are at least three isssues in your code:
You are probably iterating through some text nodes which don't have a .querySelector() method.
You are not initializing your for loop iteration variable i
You have an undeclared variable lineBoxList you are attempting to use.
You can simplify things by just using .querySelectorAll() and letting the selector do more of the work for you.
function addToppingsToAll (toppings) {
var toppingItems = document.querySelectorAll("#PizzaBoxHolder h6");
for (var i = 0; i < toppingItems.length; i++) {
toppingItems[i].textContent = "You have " + toppings " on your pizza";
}
}
querySelector is a method that appears on HTML Element Nodes. One or more of the childNodes must be some kind of node that is not an Element (such as Text Nodes or Comment Nodes).
This is probably most easily resolved with:
var PizzaBoxList = document.querySelector("#PizzaBoxHolder > *");
Related
I know, based on this error lot of questions available in SO but my problem is bit different.
I'm using for each loop to get the id and text of the elements as below
function iterateId(id){
$("input[id*='" + id + "']").each(function(){
var idOfRadioButton = $(this).attr('id');
var textOfRadioButton = $(this).closest("div").children("label").first().text();
console.log(textOfRadioButton);
console.log(idOfRadioButton);
});
}
i'm passing id's from the array by using for loop as below
window.radioButtonOrNot = function(inputArray){
var array = inputArray;
for (i = 0; i < array.length; i++) {
console.log("Came " + array[i]);
iterateId(array[i]);
}
};
When i'm following the above approach, getting the error Uncaught ReferenceError: $ is not defined at iterateId. Any one know where i'm doing the mistake
Edit
I've included jQuery also. Following is the working scenario
window.setText = function(id, text){
if($("input[id$='" + id + "']").is(':visible')){
$("input[id$='" + id + "']").val(text);
}
};
As said by freedomn-m, may be my code is running before Jquery initialization. So, I've followed the below approach. Following approach is not a solution, but it's an alternate way to achieve the solution
I've used JavaScript instead of jQuery as below
var inputId = document.querySelectorAll("input[id*='" + id + "']");
for(i = 0; i < inputId.length; i++){
console.log(inputId[i].id);
if(document.getElementById(inputId[i].id) != null){
console.log(document.querySelector('label[for*='+ inputId[i].id +']').innerHTML);
}
}
Now everything working fine...
I got to the point with my project where I decided to simplify some of the js functions where I am looking for a parent in a DOM tree, then drill down to the elements many many times in one function. instead I though I will make instances of a function which will keep some data so then I can refer and operate on objects in easy way. I got it working but as I was going along, I decided to extend functionality and add some extra functions like getElementsByClassNameThenTagName.
I loop through the arrays and if add matching elements to the array.
I have noticed (sadly only now) that I am creating an array with elements rather than HTML collection. As a results, I cannot refer to the objects in my findings by typing buttons['reset'].disabled = false;. I can access my reset button by buttons[3].disabled = false; but this would cause a lot of inconvenience.
I am therefore looking for a way to convert my array with object into a HTML collection.
Please see below my current function:
this.getElementsByClassNameThenTagName = function (elementClass, elementTag) {
if (parentNode == null) {
this.init();
}
var results = [];
var regexStr = elementClass;
var regex = new RegExp(regexStr);
var x = moduleNode.getElementsByClassName(elementClass);
// console.log(x);
var y;
for ( var i = 0; i < x.length; i++ ) {
// console.log(i);
y = x[i].getElementsByTagName(elementTag);
// console.log(y);
for (var k=0; k<y.length; k++){
// console.log(y[k]);
results.push(y[k]);
}
// console.log(results);
}
return results;
};
Any suggestions please?
Thanks.
this.getElementsByClassNameThenTagName = function (elementClass, elementTag) {
if (parentNode == null) {
this.init();
}
var results = {}; // thid should be an object (collection)
var x = moduleNode.querySelectorAll("." + elementClass + " " + elementTag);
x.forEach(function(y) {
var name = y.getAttribute("name"); // if you really sure that all the matched elements have names
results[name] = y;
});
return results;
};
Now you can use the results array like this:
var someElement = results['some name'];
NOTE: All the matched elements x should have a name attribute, and all the name attributes of the matched elements should be unique.
I have an array of 10 elements. At first I want to shuffle the array elements and display them (my current code does this). Then I want to show an alert message if any of the displayed array elements are clicked. This is the thing I am having problem with. If, I am doing onclick, it's showing me only 1 array element instead of all the 10 array elements and also showing the following error in console Uncaught TypeError: Cannot set property 'onclick' of undefined. My code is (I am using only javascript):
<script>
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var myArray = ['1','2','3','4','5','6','7','8','9','10'];
newArray = shuffleArray(myArray);
for (i=0;i<newArray.length;i++) {
var p = document.write(newArray[i] + "<br >");
p.onclick = showAlert; // this is showing me only 1 array element and also showing error in concole
}
function showAlert() {
alert("onclick Event detected!")
}
</script>
You need to create an actual element, rather than trying to bind events to strings:
for (i=0;i<newArray.length;i++) {
var p = document.createElement('p');
p.innerHTML = newArray[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
http://jsfiddle.net/92fRb/1/
Cannot set property 'onclick' of undefined
Here's your problem... p is undefined.
Why?
Because document.write does not return a DOM element. Actually it does not return anything at all (or, returns undefined).
You want to:
Use document.createElement() to create an element.
Use p.innerHTML to set the content (inner HTML) of your new element.
Append your new element to the document.
Your code can be revised as suggested in #Johan's answer.
for (i=0;i<newArray.length;i++){
var p = document.write("<span class='no'>"+newArray[i] + "</span><br />");
}
function showAlert(){
alert("onclick Event detected!")
}
for(i=0;i<document.getElementsByClassName("no").length;i++){
document.getElementsByClassName("no")[i].onclick=showAlert;
}
Beginner JS here, hope anyone could explain this to me.
1) Why does this not work:
var allSpans = document.getElementsByTagName('span');
allSpans.onclick = function() {
alert('hoo');
};
2) or if I have all the innerHTML from spans in an array and I try this:
var allSpans = document.getElementsByTagName('span');
var arrayNumbers = [];
for (var i = 0; i < allSpans.length; i++) {
var operator = allSpans[i].innerHTML;
}
arrayNumbers.onclick = function() {
alert('hoo');
};
onclick is a property of HTMLElementNode objects. getElementsByTagName returns a NodeList. Assigning a property to a NodeList doesn't assign it to every member of that list.
Exactly the same, except you are dealing with an Array instead of a NodeList.
You have to iterate through the returned list
var allSpans = document.getElementsByTagName('span');
for ( var i = 0; i < allSpans.length; i += 1 ) {
allSpans[i].onclick = function (event) {
alert('hoo');
};
}
To answer your first question, you have to add this on each node instead of the nodeList, which is what you're getting when you call document.getElementsByTagName. What you're looking for is:
for(var i = 0; i < allSpans.length; i++){
allSpans[i].onClick = function(){
alert('hoo');
};
}
You have a similar issue in the second question, except it doesn't appear as if you're actually adding anything to the arrayNumbers array, so even if you looped through that, you wouldn't get the expect events on click.
var AppPatientsList = JSON.parse(JSON RESPONSE);
var AppPatientsListSort = AppPatientsList.sort(function(a,b){
return a.firstName.toLowerCase() <b.firstName.toLowerCase()
? -1
: a.firstName.toLowerCase()>b.firstName.toLowerCase()
? 1 : 0;
});
var DataArray = [];
for (var i = 0; i < AppPatientsListSort.length; ++i) {
if (AppPatientsListSort[i].firstName === search.value) {
var appointment = {};
appointment.PatientID = AppPatientsListSort[i].PatientID;
appointment.ScheduleDate = AppPatientsListSort[i].ScheduleDate;
alert(appointment.ScheduleDate); // Works fine, i get the date...
}
DataArray[i] = appointment;
}
var RowIndex = 0;
var ScheduleDate = "";
for (i = 0, len = DataArray.length; i < len; i++) {
// Throws me error in this place... WHY?
if (ScheduleDate != DataArray[i].ScheduleDate) {
ScheduleDate = DataArray[i].ScheduleDate;
}
}
What's wrong with this code, why i am not able to access the ScheduleDate?
You are only initializing the appointment variable when you are inside the if clause, but you are adding it to the array on every iteration.
If the first element of AppPatientsListSort does not have the value you search for, DataArray[0] will contain undefined.
In the second loop you then try to access DataArray[0].ScheduleDate which will throw an error.
Update:
Even more important, as JavaScript has no block scope, it might be that several entries in DataArray point to the same appointment object.
Depending on what you want to do, everything it takes might be to change
DataArray[i] = appointment;
to
DataArray.push(appointment);
and move this statement inside the if clause so that only appointments are added that match the search criteria.
Further notes: To have a look what your DataArray contains, make a console.dir(DataArray) before the second loop and inspect the content (assuming you are using Chrome or Safari, use Firebug for Firefox).