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?
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.
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.
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.
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).
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With