Jake Jake - 2 months ago 16
CSS Question

jQuery toLowerCase and then apply Capitalize CSS Style

I have some html link values I need to convert from UPPERCASE back to LOWERCASE and then style with capitalization... The root of the problem is the fact it comes it already arrives as uppercase but I can't help that so this is my workaround:

The HTML:

<div class="block1">
<p><a href="#">SECTION TITLE</a></p>
<ul>
<li><a href="#">LINK TITLE</a></li>
<li><a href="#">LINK TITLE</a></li>
<li><a href="#">LINK TITLE</a></li>
<li><a href="#">LINK TITLE</a></li>
<li><a href="#">LINK TITLE</a></li>
<li><a href="#">LINK TITLE</a></li>
<li><a href="#">LINK TITLE</a></li>
</ul>
</div>


The jQuery:

jQuery('.block1 ul li a').each(function() {
var linkText = jQuery(this).html();
linkText.toLowerCase();
jQuery(this).css("text-transform", "capitalize");
});


At the moment, I am not seeing a conversion back to lowercase via
linkText.toLowerCase();
I do see the text-transform code being added to each link but that's it.

Fiddle

Answer

You change the variable, linkText, but you don't assign the lower-cased string to the <a> element. Instead, try:

jQuery('.block1 ul li a').each(function() {
  var linkText = jQuery(this).html();
  jQuery(this).text( linkText.toLowerCase() );
  jQuery(this).css("text-transform", "capitalize");
});

Or, much more simply:

jQuery('.block1 ul li a').text(function(index, currentText) {
    return currentText.toLowerCase();
}).css('text-transform', 'capitalize');

Or, more sensibly, simply use a CSS class to target all the relevant elements and add that class to those elements:

jQuery('.block1 ul li a').text(function(index, currentText) {
    return currentText.toLowerCase();
}).addClass('capitalize');

Along with the CSS class:

.capitalize {
    text-transform: capitalize;
}