How to underline all words of a text using jQuery ?
Given a statement and the task is to underline all the text words of HTML page using jQuery. We will use text-decoration property to add underline to each words.
HTML code:
HTML
<!DOCTYPE html> < html > < head > < style > p span { text-decoration: underline; } </ style > < script src = "https://code.jquery.com/jquery-git.js" > </ script > </ head > < body > < h2 >w3wiki</ h2 > < h2 > How to underline all the words of a text using jQuery? </ h2 > < p > Beginner For Beginner. A computer science portal for Beginner. </ p > </ body > </ html > |
jQuery Code:
$( 'p' ).each( function () { var text_words = $( this ).text().split( ' ' ); $( this ).empty().html( function () { for (i = 0; i < text_words.length; i++) { if (i === 0) { $( this ).append( '<span>' + text_words[i] + '</span>' ); } else { $( this ).append( ' <span>' + text_words[i] + '</span>' ); } } }); }); |
Final code: The following code is the combination of the above two code snippets.
<!DOCTYPE html> < html > < head > < style > p span { text-decoration: underline; } </ style > < script src = "https://code.jquery.com/jquery-git.js" > </ script > </ head > < body > < h2 >w3wiki</ h2 > < h2 > How to underline all the words of a text using jQuery? </ h2 > < p > Beginner For Beginner. A computer science portal for Beginner. </ p > < script > $(document).ready(function () { $('p').each(function () { var text_words = $(this).text().split(' '); $(this).empty().html(function () { for (i = 0; i < text_words.length ; i++) { if (i === 0) { $(this).append('<span>' + text_words[i] + '</ span >'); } else { $(this).append(' < span >' + text_words[i] + '</ span >'); } } }); }); }); </ script > </ body > </ html > |
Output:
Supported Browsers are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Opera
- Safari
Contact Us