Skip to content Skip to sidebar Skip to footer

How To Add Additional Attribute According To The Text

This is my HTML Code
9 , 6

Solution 1:

Just iterate and set classes.

$('#ccc_new_val_hdn span').each(function() {
    if($(this).html() == ','){
        $(this).addClass('comma');
    }
    if($(this).html() == ' '){
        $(this).addClass('space');
    }
});

Demo: http://jsbin.com/igaraq


Solution 2:

You can just select all the spans inside the div and trim and then check the values, after that you can just set which class you want to apply.

$(document).ready(function(){
    $('#ccc_new_val_hdn span').each(function(){
        var text = $.trim($(this).text());
        if(text === ',')
            $(this).addClass('comma')
        else if(text === "")
            $(this).addClass('space');
    });
});

Solution 3:

alternatively .text() would suffice

$('#ccc_new_val_hdn span').each(function() {
    if($(this).text() == ','){
        $(this).addClass('comma');
    }
    if($(this).text() == ' '){
        $(this).addClass('space');
    }
});

Solution 4:

Browsers may behave differently when you have an element that contains a single whitespace character. Safari, for instance, simply removes it on parsing while Firefox preserves it.

jQuery's :contains filter may not be very useful as it does a search anywhere in the element's text content, but it looks like you want to do an exact search. The problem with :contains is that when searching for an element with just a comma, it will match all these:

<span>,</span>
<span>hello, world</span>
<span> , </span>

The second, and third elements will match both a comma and a space.

Here's a custom jQuery filter that is similar to :contains, but does an exact text match instead.

jQuery.expr[':'].hasText = function(element, index, meta) {
    var textToSearch = meta[3];
    return $(element).text() == textToSearch;
};

Use it as :hasTexT(..). Here's an example of how to select elements by their text content and change their CSS class.

$(':hasText(,)').addClass('comma');
$(':hasText( )').addClass('space');

Here's an example. Try it in Firefox. Other browsers may eat up the single whitespace.


Post a Comment for "How To Add Additional Attribute According To The Text"