javascriptparsingdomsession-storage

Failing to extract an ID from an InnerHTML string segment stored in sessionStorage


The teo lines in the script section of my html page are these ...

 var mySession = sessionStorage.getItem("catProfile");
 var myValue = mySession.getElementByID("catAge");

The mySession variable correctly returns the stored string which is the inner html of a larger element. The stored/retrieved variable looks like this...as you can see the ID catAge, exists, but the myValue variable is erroring out, not finding it, am I using the wrong technique? Any help appreciated.

      <img class="profile-photo" src="/images/cats/vimes.webp">
      <img class="care-icon" src="" <="">
      <p class="name">Sir Vimes</p>
      <p id="catAge" class="age">3 años</p>

      <div class="details">
        <img class="photo-one" src="/images/cats/vimes_one.webp" loading="lazy">
        <img class="photo-two" src="/images/cats/vimes_two.webp" loading="lazy">
        <img class="photo-three" src="/images/cats/vimes_three.webp" loading="lazy">

        <p class="title">Beautiful, Playful and Affectionate Calico</p>
        <p class="story">
          This cat was found by the side of the street in a cardboard box,
          she was hungry and wet from being in the rain. She has a wonderful
          personalty, is friendly and loving.
        </p>
        <p class="health">No health issues</p>
        <p class="gender">Female</p>
        <p class="fee">$50.000 COP</p>
        <p class="cuddle-factor">3</p>
        <p class="activity-factor">7</p>
        <p class="cat-friendly">yes</p>
        <p class="dog-friendly">no</p>
      </div>
    

    

Solution

  • Because mySession is a string. That string contains HTML code, but it's still just a string as far as JavaScript is concerned.

    One approach could be to create an element to wrap that HTML code, add the HTML code to it, and then query that element. For example:

    // fetch string from storage
    var mySession = sessionStorage.getItem("catProfile");
    
    // create element
    var myElement = document.createElement("div");
    
    // add string to element as inner HTML
    myElement.innerHTML = mySession;
    
    // get the element you want from that in-memory element
    var myValue = myElement.querySelector("#catAge");
    

    Note also the use of querySelector instead of getElementById, and the addition of a # character to the selector used.