Styling First Word Of Any Element With jQuery And CSS

File Size: 2.77 KB
Views Total: 7296
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Styling First Word Of Any Element With jQuery And CSS

A minimalist jQuery solution to apply custom CSS styles to the first word of any elements just like the ::first-letter pseudo-element in CSS.

How to use it:

1. Wrap your text into any container element with the CSS class of 'st-word'.

<h1 class="st-word">jQuery First Word Selector Demo</h1>

2. Include the necessary jQuery library on the webpage.

<script src="//code.jquery.com/jquery.min.js"></script>

3. The main jQuery script to wrap the first word of your element into a span element with the CSS class of 'first-word'.

$(".st-word").each(function() {
  // Some Vars
  var elText,
      openSpan = '<span class="first-word">',
      closeSpan = '</span>';
  
  // Make the text into array
  elText = $(this).text().split(" ");
  
  // Adding the open span to the beginning of the array
  elText.unshift(openSpan);
  
  // Adding span closing after the first word in each sentence
  elText.splice(2, 0, closeSpan);
  
  // Make the array into string 
  elText = elText.join(" ");
  
  // Change the html of each element to style it
  $(this).html(elText);
});

4. Style the first word whatever you like:

.first-word {
  color: #F44336;
}

This awesome jQuery plugin is developed by ahmedbeheiry. For more Advanced Usages, please check the demo page or visit the official website.