Home > Web Front-end > JS Tutorial > Use jQuery to Create Excerpts for Text Elements

Use jQuery to Create Excerpts for Text Elements

Christopher Nolan
Release: 2025-03-04 00:15:10
Original
526 people have browsed it

Use jQuery to Create Excerpts for Text Elements

Use jQuery to Create Excerpts for Text Elements

This is how you can use jQuery to limit characters inside a textarea. It is a function to set the maximum length of characters for any page element. You could use it to create excerpts for posts on your blog for example. See more jQuery .each Examples.

Demo

<span>(function($) { 
</span>	<span>// jQuery function to set a maximum length or characters for a page element it can handle mutiple elements
</span>        $<span>.fn.createExcerpts = function(elems<span>,length,more_txt</span>) {
</span>		$<span>.each($(elems), function() { 
</span>			<span>var item_html = $(this).html(); //
</span>			item_html <span>= item_html.replace(/< <span>/<span>?<span>[^>]</span>+></span>/gi</span>, ''); //replace html tags
</span>			item_html <span>= jQuery.trim(item_html);  //trim whitespace
</span>			<span>$(this).html(item_html.substring(0,length)+more_txt);  //update the html on page
</span>		<span>});
</span>		<span>return this; //allow jQuery chaining 
</span>	<span>}
</span><span>})(jQuery);</span>
Copy after login

And this is how you use it:

<span>//example call
</span><span>$().createExcerpts('.blogpost',280,'...');</span>
Copy after login

The above is the detailed content of Use jQuery to Create Excerpts for Text Elements. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template