How to get texts around the image on a web page using javascript like a search engine?…
- User
How to get texts around the image on a web page using javascript like a search engine? the texts may be above the image and may be below the image. there may be even more scenarios. Can you consider as many as possible scenarios.
- Assistant
To get the text around an image, you can use the
NodeandElementAPIs to traverse through the sibling and parent elements. Here's a function that covers most scenarios:function getTextAroundImage(imgElement) { const maxSearchDepth = 3; const getText = (element) => { let text = ''; if (element.nodeType === Node.TEXT_NODE) { text += element.textContent.trim(); } else if (element.nodeType === Node.ELEMENT_NODE) { text += element.tagName === "IMG" ? "" : element.innerText.trim(); } return text; }; const searchSiblings = (element, depth) => { if (!element || depth > maxSearchDepth) { return ''; } let text = ''; text += searchSiblings(element.previousSibling, depth + 1); text += ' ' + getText(element); text += ' ' + searchSiblings(element.nextSibling, depth + 1); return text; }; const searchParents = (element) => { if (!element || element.tagName === 'BODY') { return ''; } let text = ''; text += searchSiblings(element.previousSibling, 0); text += ' ' + searchParents(element.parentElement); text += ' ' + searchSiblings(element.nextSibling, 0); return text; }; return searchParents(imgElement); } // Usage: const imgElement = document.querySelector('img'); // or any other way to get the img element const text = getTextAroundImage(imgElement); console.log(text);
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.