1

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>

4 Answers 4

5

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/

Sign up to request clarification or add additional context in comments.

2 Comments

(close the class attributes before data)
This would be a brilliant method to use, unfortunately data-year cannot be set, it can only be used as a class at the moment. But great answer!
1

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/

Comments

0
$('[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])
                }
            }
        });

Comments

0

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);
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.