Reputation: 217
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
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
Reputation: 175
You could try
$('div').each(function() {
$(this).addClass($(this).attr('id').replace('unique', 'blog'));
});
Upvotes: 4
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