Highlighting Text with JavaScript
Highlighting text on a web page is a useful feature for emphasizing important information or drawing attention to specific content. While various techniques exist, this article explores a simple JavaScript implementation:
Code Snippet:
The provided JavaScript function, highlight(), effectively highlights the first occurrence of a specified text within a given HTML element (e.g., a paragraph). Here's how it works:
Example Usage:
To utilize this function, include the JavaScript code in your HTML document and attach an onClick event to a button or link. When clicked, the event will trigger the function call, passing the text to be highlighted as a parameter. For instance:
<button onclick="highlight('fox')">Highlight</button> <div>
In this example, clicking the button will highlight the first occurrence of the word "fox" in the "inputText" element.
CSS Customization:
You can further customize the highlighted appearance by overriding the styles for the "highlight" class in your CSS. The given example applies a yellow background color to the highlighted text, but you can tweak it to suit your design needs.
By applying these techniques, you can easily highlight specific text on a web page, enabling users to quickly locate and focus on important information.
The above is the detailed content of How Can I Highlight Text on a Web Page Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!