Hasanul February 2016

jQuery count div by class and then get the inner div's id string

I'm trying to count the total div by class name and then get the specific part of inner div's id. Here is my example,

<div class=”my_block1”>
    <div class=”my_block2”>
        <div id=”my-style-35-area”>
            some contents
        </div>
    </div>
</div>
<div class=”my_block1”>
    <div class=”my_block2”>
        <div id=”my-style-36-area”>
            some contents
        </div>
    </div>
</div>
<div class=”my_block1”>
    <div class=”my_block2”>
        <div id=”my-style-38-area”>
            some contents
        </div>
    </div>
</div>

So, I need to figure out that 35, 36, 38 from the ID's. Anyone can help me with this please? Thanks in advance.

Answers


Azim February 2016

You can get 35, 36, 38 in an array using map() function like following.

var num = $('div[id^="my-style-"]').map(function () {
    return this.id.split('-')[2];
}).get();
console.log(num

BTW in you html you have used instead of ".


DinoMyte February 2016

To count the number of div with a specific class:

$('.my_block1').length // would give you 3

and to get the ids inside that div :

$('.my_block1').find('[id^=my-style-]').each(function()
{
   alert(this.id.split('-')[2]); // give you the ids of each div
});

Example : https://jsfiddle.net/ytzLgx0q/

Post Status

Asked in February 2016
Viewed 1,330 times
Voted 11
Answered 2 times

Search




Leave an answer