Is it possible to get the source of an HTML element of a particular area/part of a web page? Like sometimes we open our browser open a website hover over a button or element and inspect it and we can see all the code for example <div class="fs-body2 bb bc-black-225 bg-black-100 p12"> Introduce the proble </div>
and we can see that particular element code in my case I hover over ‘ Introduce the problem’ and just inspect it and I get that source.
Currently, my code doesn’t work on every HTML code it return null in most cases if the HTML code is too large.
import fs from "fs";
import { JSDOM } from "jsdom";
function findTextInHTML(filePath, targetText) {
const htmlCode = fs.readFileSync(filePath, "utf8");
const dom = new JSDOM(htmlCode);
const document = dom.window.document;
function searchText(element) {
if (element.textContent.includes(targetText)) {
return element;
}
if (element.outerHTML.includes(targetText)) {
for (const child of element.children) {
const result = searchText(child);
if (result) {
return result;
}
}
return element;
}
return null;
}
const foundElement = searchText(document.body);
return foundElement ? foundElement.tagName.toLowerCase() : null;
}
const htmlFilePath = "index.html";
const searchText = "Get Started";
const result = findTextInHTML(htmlFilePath, searchText);
console.log(result);