KulerGary
KulerGary

Reputation: 217

Check The ID of an Array of Divs and Add A Class Name with the same Number

I have a list of entries like this:

<div id="unique-entry-id-4">
<div id="unique-entry-id-3">
<div id="unique-entry-id-2">
<div id="unique-entry-id-1">
<div id="unique-entry-id-0">

What I want to accomplish is this:

<div id="unique-entry-id-4" class="blog-entry-id-4">
<div id="unique-entry-id-3" class="blog-entry-id-3">
<div id="unique-entry-id-2" class="blog-entry-id-2">
<div id="unique-entry-id-1" class="blog-entry-id-1">
<div id="unique-entry-id-0" class="blog-entry-id-0">

I know that I can do something like this:

$("div[id^='unique-entry-id-0']").each(function(i) {
    $(this).attr('class', "blog-entry-id-0");
});
repeat for each div

But what I'd like to to is use the minimum amount jQuery to read the ID name and number and then add a class that has the same number.

Upvotes: 1

Views: 44

Answers (3)

AlexBerd
AlexBerd

Reputation: 1504

If you div's have a parent and if their id`s are in descending order, then try this one:

var length=$(#parentDiv>div).length;
$(#parentDiv>div).each(function(){
var className='blog-entry-id-'+(length-$(this).index())
$(this).addClass(className);
});

Upvotes: 0

goupil
goupil

Reputation: 175

You could try

$('div').each(function() {
    $(this).addClass($(this).attr('id').replace('unique', 'blog'));
});

Demo

Upvotes: 4

RiccardoC
RiccardoC

Reputation: 866

$(document).ready(function () {
    $("div[id^='unique-entry-id']").each(function(i) {
        var divId = $( this ).attr( "id" );
        var spittedId = divId.split( "-" );
        var divClass = "blog-entry-id-" + spittedId[3];
        $( this ).addClass( divClass );
    });
});

If you are sure that the difference between "id" and "class" is only the "unique" "blog"

$(document).ready(function () {
    $("div[id^='unique-entry-id']").each(function(i) {
        $( this ).addClass( $( this ).attr( "id" ).replace( "unuique", "blog" ) );
    });
});

Upvotes: 1

Related Questions