Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element.querySelector is undefined

Tags:

javascript

dom

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";
    }
}
like image 875
Bill Bllson Avatar asked Oct 24 '15 22:10

Bill Bllson


2 Answers

There are at least three isssues in your code:

  1. You are probably iterating through some text nodes which don't have a .querySelector() method.
  2. You are not initializing your for loop iteration variable i
  3. 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";
    }
}
like image 68
jfriend00 Avatar answered Oct 29 '22 11:10

jfriend00


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 > *"); 
like image 38
Quentin Avatar answered Oct 29 '22 12:10

Quentin