I can't say I'm 100% sure of what it is you're asking for but if you're asking for a way to make the code you have more generic, you can make things more dynamic by amending both the HTML and Javascript as so:
<p id="abc" data-image="def"></p>
<img id="def">
const images = [
{ value: '1001', image: 'img/new/img14.webp' }
];
function load_image(elementId, storageId) {
const storage = sessionStorage.getItem(storageId);
const p = document.getElementById(elementId);
p.innerHTML = storage;
for (const image of images) {
if (storage === image.value) {
const targetId = p.getAttribute('data-image');
const target = document.getElementById(targetId);
target.src = image.image;
break;
}
}
}
window.addEventListener('load', () => {
load_image('abc', 'favoriteMovie');
});
What this does is introduce a function containing your logic which accepts an
elementId
representing the ID of the HTML element containing the text you want to compare, and
storageId
representing the name of the session storage variable.
The
images
variable is an array of each value along with the image path. The function gets the HTML element and gets the text, then it loops over the images and compares the image value with the inner HTML of the element. If the value matches, it then uses this
data-image
attribute to locate the corresponding
<img>
element and updates the
src
attribute to point to the image.
This means you can add any number of elements and images to the path and just call the
load_image
function with the correct element ID and session storage key.