Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

javascript - Group divs by attribute

Based on this SO I try to group divs by its div attribute "messsage-id". So all divs with the same "message-id" should be wrapped by a div with class name group.

<div class="message" message-id="1">a</div>
<div class="message" message-id="1">a</div>
<div class="message" message-id="2">a</div>
<div class="message" message-id="2">a</div>
<div class="message" message-id="3">a</div>

But I dont get it to work with attributes instead of class names. Here is what I tried:

var groups = {};
$('.day').each(function () {
    var className = this.getAttribute("message-id").match(/(dayd+)/)[1],
        $group = groups[className];
    if (!$group) {
        $group = $('<div />', {
            'class': 'group'
        }).insertAfter(this);
        groups[className] = $group;
    }
    $group.append(this);
})

Here is the Fiddle

question from:https://stackoverflow.com/questions/65923907/group-divs-by-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You were on the right path with the getAttribute function but don't need the use the match function in your code since getAttribute already returns the id for your groups. Also, your $('.day') is not targeting the right class for your loop, it should be targeting $('.message') in your example.

var groups = {};
$('.message').each(function () { 
    var className = this.getAttribute("message-id"),
    $group = groups[className];
    if (!$group) {
        $group = $('<div />', {
            'class': 'group'
        }).insertAfter(this);
        groups[className] = $group;
    }
    $group.append(this);
})
.group {
    border: 1px solid red;
    margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="message day" message-id="1">a</div>
<div class="message day" message-id="1">a</div>
<div class="message day" message-id="2">a</div>
<div class="message day" message-id="2">a</div>
<div class="message day" message-id="3">a</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...