简体   繁体   中英

jquery get certain class name of element which has several classes assigned

I need to read elements class name. I have elements like this:

<article class="active clrone moreclass">Article x</article>
<article class="active clrtwo moreclass">Article y</article>
<article class="active clrthree moreclass moreclass">Article z</article>
<article class="active clrone moreclass">Article xyza</article>

I need to parse out class name that starts with clr . So if second element was clicked then I would need to get clrtwo className.

You can use a regular expression match on the class name of the clicked item to find the class that begins with "clr" like this:

$("article").click(function() {
    var matches = this.className.match(/\bclr[^\s]+\b/);
    if (matches) {
        // matches[0] is clrone or clrtwo, etc...
    }
});

Here is solution for you:

$('article').click(function () {
    var className = this.className.split(' ');
    for (var i = 0; i < className.length; i+=1) {
        if (className[i].indexOf('clr') >= 0) {
            alert(className[i]);
        }
    }
});

http://jsfiddle.net/vJfT7/

There's no matter how you're going to order the different classes. The code will alert you a class name only of there's 'clr' as a substring in it.

Best regards.

If you don't need to find elements based on these classes (eg doing $('.clrtwo') ) it would be nicer to store the data as a data-clr attribute. This is standards-compliant from HTML5, and is supported by jQuery using the .data() function.

In this instance, I would modify your HTML in this way:

<article class="active moreclass" data-clr="one">Article x</article>
<article class="active moreclass" data-clr="two">Article y</article>
<article class="active moreclass moreclass" data-clr="three">Article z</article>
<article class="active moreclass" data-clr="one">Article xyza</article>

I would then use Javascript like this:

$('article.active').click(function() {
    console.log($(this).data('clr'));
});

jsFiddle example

If it is always the second class name which is of interest you can do this:

$("article").click(function () {

    // split on the space and output the second element
    // in the resulting array
    console.log($(this)[0].className.split(" ")[1]);
});

http://jsfiddle.net/karim79/Z3qhW/

Use an attribute selector to get those that have class names that contain clr .

From there:

  • extract the class name (string functions)
  • analyze the position
  • determine the next element

The latter two might be best served by a translation array if you only had a few classes.

UPDATE

I agree with lonesomeday , you'd be far better off using data-* attribute to handle such logic. Using CSS as JavaScript hooks is a thing of the past.

<script type="text/javascript">
jQuery(document).ready(function(){
  $("article").click(function(){
   alert($(this).attr('class').match(/\bclr[^\s]+\b/)[0]);
  });
});
</script>

This should jquery script should do what you asked (tested on jsfiddle):

$(document).ready(function () {
    function getClrClass(elem) {
        var classes = elem.getAttribute('class').split(' ');
        var i = 0;
        var cssClass = '';

        for (i = 0; i < classes.length; i += 1) {
            if (classes[i].indexOf('clr') === 0) {
                cssClass = classes[i];
                i = classes.length; //exit for loop
            }
        }

        return cssClass;
    };
    $('article').click(function (e) {
        var cssClass = getClrClass($(this)[0]);
        alert(cssClass);
        e.preventDefault();
        return false;
    });
});

Hope this helps.

Pete

http://jsfiddle.net/4KwWn/

$('article[class*=clr]').click(function() {
    var token = $(this).attr('class'),
        position = token.indexOf('clr');

    token = token.substring(position, token.indexOf(' ', position));

    alert(token);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM