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

javascript - jQuery. Select all the elements that classname starts with - Stack Overflow

programmeradmin1浏览0评论

If I have elements with classnames like this:

   .ses_0 .ses_1 .ses_2 .ses_3  

How can I select all the elements and prepend those with some snippet? Something like this:

    var sessions = $('*[class*=ses_]');

    for (var i = 0; i < sessions.length; i++)
    {
        sessions [i].prepend("<img src='/Content/img/caticon"+i+".png' />");
    }

That doesn't work of course.

Edit: Ahhhh... damn It seems that I need to get not only those classes that start with .ses_ but also <a> elements within. How can I do that?

Basically something that works $(".ses_0 a") , only I need to get all the classes start with ses_

If I have elements with classnames like this:

   .ses_0 .ses_1 .ses_2 .ses_3  

How can I select all the elements and prepend those with some snippet? Something like this:

    var sessions = $('*[class*=ses_]');

    for (var i = 0; i < sessions.length; i++)
    {
        sessions [i].prepend("<img src='/Content/img/caticon"+i+".png' />");
    }

That doesn't work of course.

Edit: Ahhhh... damn It seems that I need to get not only those classes that start with .ses_ but also <a> elements within. How can I do that?

Basically something that works $(".ses_0 a") , only I need to get all the classes start with ses_

Share Improve this question edited Mar 23, 2011 at 21:57 iLemming asked Mar 23, 2011 at 21:33 iLemmingiLemming 36.2k61 gold badges198 silver badges316 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 23

You're almost there:

// selects all that start with "ses_"
var sessions = $('[class^="ses_"]');

Even though your loop should work, you could also use the

sessions.each(function(index){
    this.prepend(... // and so on
});

You can use the attribute starts with selector in jQuery: http://api.jquery.com/attribute-starts-with-selector/

Beware that it's not nearly as fast as using the regular way of selecting elements.

发布评论

评论列表(0)

  1. 暂无评论