Skip to content Skip to sidebar Skip to footer

Apply CSS Style To Span Tag Based On Content

I don't know if this is possible, but I am trying to apply a style to a span tag based on its content. I have some tags on a blog site that are stored in a span tag and would like

Solution 1:

  1. Use . instead of # for col-cell since it is referring to a class
  2. Use a space between col-cell and span to indicate you are searching for children
  3. Within :contains() itself, do not use quotes

$('.col-cell span:contains(c)').css('color', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="col-cell">
  <span>cloud</span>
  <span>business</span>
  <span>social</span>
</div>

Update

hi i have managed to get it to work now, thank you, there one other thing, i would like to use another selector instead of :contain, and use a selector based on the first character of the word

From jQuery selector that simulates :starts-with or :ends-with for searching text?

$.extend($.expr[":"], {
    "starts-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // first index is 0
        return text.indexOf(term) === 0;
    },

    "ends-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // last index is last possible
        return text.lastIndexOf(term) === text.length - term.length;
    }
});
$('span:starts-with(c)').css('color', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="col-cell">
  <span>cloud</span>
  <span>business</span>
  <span>social</span>
</div>

Post a Comment for "Apply CSS Style To Span Tag Based On Content"