परिचय
पेज लोड होने पर विशिष्ट शब्दों को हाइलाइट करने के लिए, टेक्स्ट को शब्दों में विभाजित करें, लक्ष्य शब्दों की जांच करें, और उन्हें स्टाइल्ड <span> एलिमेंट्स में लपेटें। यह क्लाइंट-साइड हाइलाइटिंग के लिए एक सरल दृष्टिकोण है।
उदाहरण
<!DOCTYPE html> <html lang="hi"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>टेक्स्ट हाइलाइट</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <style> .yellow { color: yellow; background: black; padding: 2px; } .blue { color: blue; font-weight: bold; } </style> </head> <body> <h1 id="pageLoads">मेरे पीले शब्द, आपके नीले शब्द</h1> <script> const element = document.getElementById('pageLoads'); const words = element.innerHTML.split(' '); for (let i = 0; i < words.length; i++) { if (words[i] === 'नीले') { words[i] = '<span class="blue">' + words[i] + '</span>'; } if (words[i] === 'पीले') { words[i] = '<span class="yellow">' + words[i] + '</span>'; } } element.innerHTML = words.join(' '); </script> </body> </html>
आउटपुट

चलाने के निर्देश
उपरोक्त प्रोग्राम को चलाने के लिए, फ़ाइल का नाम anyName.html (index.html) सेव करें और फ़ाइल पर राइट-क्लिक करके VS कोड एडिटर में "Open with Live Server" विकल्प चुनें।
सुधारित दृष्टिकोण (टेक्स्ट नोड्स सुरक्षित)
function highlightWords(element, wordsToHighlight, className) {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
const textNodes = [];
while (walker.nextNode()) textNodes.push(walker.currentNode);
textNodes.forEach(node => {
let text = node.textContent;
wordsToHighlight.forEach(word => {
const regex = new RegExp(`(\\b${word}\\b)`, 'gi');
text = text.replace(regex, `<span class="${className}">$1</span>`);
});
if (text !== node.textContent) {
const span = document.createElement('span');
span.innerHTML = text;
node.parentNode.replaceChild(span, node);
}
});
}
// उपयोग
highlightWords(document.body, ['पीले', 'नीले'], 'highlight');
यह दृष्टिकोण HTML टैग्स को नहीं तोड़ता और केस-इनसेंसिटिव है।