Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.querySelectorAll length is always 0

Tags:

javascript

I'm trying to create some draggable boxes in javascript. I decided to make an empty class "draggable" in CSS and a "box" class. The code is as follows:

<!DOCTYPE html>
<html>

<head>
    <style>
    .draggable
    {

    }
    .box
    {
        position: absolute;
        width: 80px; height: 60px;
        padding-top: 10px;
        text-align: center;
        font-size: 40px;
        background-color: #222;
        color: #CCC;
    }
    </style>
</head>

<body>
<div class="draggable box">1</div>
<div class="draggable box">2</div>
<div class="draggable box">3</div>
<script>
    var draggableStuff = document.querySelectorAll('draggable');
    var tabLength = draggableStuff.length;
    alert(tabLength);
</script>
</body>

The problem is that tabLength is always zero. I want to get an array filled with all draggable stuff. I'm new to javascript. What have I missed here?

like image 684
Michael Avatar asked Mar 06 '12 21:03

Michael


People also ask

What does the querySelectorAll () method do?

Document.querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Why querySelectorAll not working?

Originally Answered: Why is my querySelectorAll() method not working ? Make sure that the engine is executing the method call after the content, you are interested in, is loaded into the DOM. If you are constructing the query selector dynamically, then make sure it is correct during execution.

What is the type of querySelectorAll?

querySelectorAll() The Element method querySelectorAll() returns a static (not live) NodeList representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called.

What is the difference between document querySelector and document querySelectorAll?

document. querySelector(selectors); It returns the first element which matches the selector. querySelectorAll() Method: The querySelectorAll() method returns all the elements within the document which matches the specified CSS selector(s).


1 Answers

You want to select elements by class, so don't forget about the dot:

var draggableStuff = document.querySelectorAll('.draggable');

Another option is to use document.getElementsByClassName:

var draggableStuff = document.getElementsByClassName('draggable');
like image 60
Rob W Avatar answered Oct 11 '22 15:10

Rob W