ngplayground
ngplayground

Reputation: 21627

jQuery Find class and store it as a Variable

I have a couple of <div> which have classes in them of timeline-year- and then the year attached.

I'm trying to find the class with the year and extract the year into a variable to append the text inside the div.

http://jsfiddle.net/ubL7h10u/

<div class="jsn-bootstrap3 timeline-events timeline-year-2012">
    Year
</div>
<div class="jsn-bootstrap3 timeline-events timeline-year-2011">
    Year
</div>

Upvotes: 1

Views: 145

Answers (4)

khollenbeck
khollenbeck

Reputation: 16157

Assuming you want the year text off of the class attribute.

$('[class*="timeline-year"]').each(function(){
    var classString = $(this).attr('class');
    var year = classString.match(/\d+$/)[0];
    console.log(year);
});

Demo:

http://jsfiddle.net/ubL7h10u/9/

Upvotes: 1

dfsq
dfsq

Reputation: 193281

One of the ways to do it using text method and a little regular expession:

$('[class*="timeline-year"]').text(function () {
    return $(this).text() + ' ' + this.className.match(/timeline-year-(\d+)?/)[1];
});

Demo: http://jsfiddle.net/ubL7h10u/8/

But you would make your code cleaner if you went with this:

<div class="jsn-bootstrap3 timeline-events" data-year="2012">Year</div>
<div class="jsn-bootstrap3 timeline-events" data-year="2011">Year</div>

and then:

$('.timeline-events').text(function () {
    return $(this).text() + ' ' + $(this).data('year');
});

or event with just CSS in this case:

.timeline-events:after {
    content: ' ' attr(data-year);
}

CSS demo: http://jsfiddle.net/ubL7h10u/10/

Upvotes: 5

enguerranws
enguerranws

Reputation: 8233

Another way to do it : get the content of class attribute, then get the last 4 characters of that string : http://jsfiddle.net/ubL7h10u/5/

$('[class*="timeline-year"]').each(function(){
        var classname = $(this).attr('class');
        var year = classname.substr(classname.length - 4);
        console.log(year);
    });

Upvotes: 0

Arun Ghosh
Arun Ghosh

Reputation: 7744

$('[class*="timeline-year"]').each(function(){
            var year = $(this);
            var list = $(this).attr("class").split(" ");
            for(var i =0; i < list.length; i++)
            {
                if(list[i].indexOf("timeline-year") !== -1)
                {
                    $(this).html(list[i].split("-")[2])
                }
            }
        });

Upvotes: 0

Related Questions