最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.querySelectorAll length is always 0 - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Mar 6, 2012 at 21:14 MichaelMichael 1,6072 gold badges20 silver badges40 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

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');

I came across this situation. Although it is too old post I would like to help people with my answer:

To select all the elements (no matter what it is, it may be div, span, h1, etc...) with particular attribute

Without value?:

var dragables = document.querySelectorAll('[draggable]');

With value?:

var dragables = document.querySelectorAll('[draggable="true"]');
发布评论

评论列表(0)

  1. 暂无评论