使用正则表达式搜索div类

use*_*306 5 html javascript regex class

听起来很简单,呵呵.我发现很多答案,但都使用jQuery或ProtoType.我想要简单的JavaScript.它不应该那么难,但JavaScript不是我的事; 没有中央文件意味着寻找年龄而不是找到我想要的东西.

请考虑以下HTML代码段:

<div class="central_0"> .. </div>
<div class="central_1"> .. </div>
<div class="central_2"> .. </div>
Run Code Online (Sandbox Code Playgroud)

现在我想使用JavaScript来处理那些DIV.

function processDivElements()
{
 // search for relevant DIV classes
 var divArray = document.getElementsByClass.regex('/^central_.*$/');

 // do stuff with the DIV elements found
 foreach (divArray as divElement)
 {
   divElement.style.background = '#f00';
 };
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我翻译成适当的 JavaScript吗?我使用的是类,而不是ID.我更喜欢使用正则表达式.

Ble*_*der 11

jQuery解决方案真的很棒:

var $divs = $('div[class^="central_"]');
Run Code Online (Sandbox Code Playgroud)

如果您只想支持更新的浏览器,您可以使用document.querySelectorAll()基本相同的东西:

var divs = document.querySelectorAll('div[class^="central_"]');
Run Code Online (Sandbox Code Playgroud)

如果你想支持旧的浏览器,代码会变得很糟糕:

var all_divs = document.getElementsByTagName('div');
var divs = [];

for (var i = 0; i < all_divs.length; i++) {
    var div = all_divs[i];

    if (div.className.match(/^central_\d+$/) {
        divs.push(div);
    }
}
Run Code Online (Sandbox Code Playgroud)

也:

我使用的是类,而不是ID.我更喜欢使用正则表达式.

您的类是唯一的,并且实际上像ID一样运行,这实际上不是类的预期用途.改为构建你的HTML:

<div id="central_0" class="central">...</div>
<div id="central_1" class="central">...</div>
<div id="central_2" class="central">...</div>
Run Code Online (Sandbox Code Playgroud)

现在,JavaScript变得更简单:

var $divs = $('.central');                               // jQuery
var divs =  document.querySelectorAll('.central');       // Newer browsers
var divs =  document.getElementsByClassName('central');  // Older browsers
Run Code Online (Sandbox Code Playgroud)