jquery getElementsByClassName查找部分类名

时间:2014-06-13 12:02:45

标签: javascript jquery html

我想使用javascript函数getElementsByClassName来循环一些没有确切类名的html div,但它以相同的文本开头:“akordeon-item”

因此,html文本如下所示:

<div class="akordeon-item akordeon-item-first">

<div>
    <span class="userid">
          blabla@yahoo.com
    </span>
</div>
</div>
<div class="akordeon-item akordeon-item-second">

<div>
    <span class="userid">
          john_doe@yahoo.com
    </span>
</div>
</div>
<div class="akordeon-item akordeon-item-third">

<div>
    <span class="userid">
          john_doe2@yahoo.com
    </span>
 </div>
 </div>

 <div class="akordeon-item akordeon-item-fourth">

<div>
    <span class="userid">
          john_doe3@yahoo.com
    </span>
</div>

另外,我试过的javascript代码就是这个:

var slides = getElementsByClassName(".akordeon-item");
for(var i = 0; i < slides.length; i++)
{
   alert("element : "+slides[i]);
}

我也试过在getElementsByClassName方法中搜索这个字符串:“akordeon-item”

如何使这个循环工作? 请帮忙......

2 个答案:

答案 0 :(得分:23)

您可以使用a bunch of special selectors

^= is starts with

$= is ends with    
=  is exactly equal
!= is not equal
*= is contains

尝试:

$.each($('[class^="akordeon-item"]'), function(key, value) {
    console.log(key, value);
});

迭代集合的其他方法:

$('[class^="akordeon-item"]').each(function(key, value) {
    console.log(key, value);
});

或使用for循环:

var slides = $('[class^="akordeon-item"]');
for (var i = 0; i < slides.length; i++) {
    console.log(slides[i]);
}

答案 1 :(得分:2)

$('div[class^="akordeon-item"]').each(function(index){});