0

I'm developing a website, that apply content editable feature to some pages, so I wanted to store it in local storage, but it only works for one element! I tried to use GetElementByClassName() and querySelectorAll(), but with no luck. Here is the code and any feedback is highly appreciated!

<header>
<section>
<div>
    <h1 class="edit" contenteditable="true" title="Edit your trip name">Trip Name</h1>
    <h3 class="edit" contenteditable="true" title="Edit your country name"> Country Name</h3>
    <a href="" class="cd-btn" onclick="saveEdits()">Save</a>        
</div> 
</section>
</header>


<section>
    <h2 title="Anything to add?">Trip Foucs</h2>
    <div class="edit" contenteditable="True" title="Anything to add?"></div>            
</section>

<script>
    function saveEdits() {

       //get the editable element
        var editElem = (document.getElementsByClassName("edit"));

      //get the edited element content
       var userVersion = editElem.innerHTML;

    //save the content to local storage
     localStorage.userEdits = userVersion;}

function checkEdits() {

    //find out if the user has previously saved edits
     if(localStorage.userEdits!=null)
     (document.getElementsByClassName("edit")).innerHTML =localStorage.userEdits;}
</script>

Thanks, Maryam

Maryam-AM
  • 89
  • 1
  • 12
  • getElementsByClassName returns an array – CaptainHere Mar 12 '17 at 18:24
  • 2
    `getElementsByClassName` returns a collection that you have to index into. – 4castle Mar 12 '17 at 18:24
  • 1
    `var editElem = (document.getElementsByClassName("edit"));` makes `editElem` a **list** of matching elements. (That's why "elements" is plural in the name.) For just the first one, add `[0]` after the call, or use `querySelector(".edit")` instead. – T.J. Crowder Mar 12 '17 at 18:25
  • Where is your call to check edits? – LiverpoolOwen Mar 12 '17 at 18:25
  • document.getElementsByClassName("edit")[0].innerHTML = localStorage.userEdits;} – CaptainHere Mar 12 '17 at 18:25
  • Than you that was helpful, Just one more question. I applied the editElem [0] it worked on a specified class which is the first one, how about if I want it to work on multiple classes which all are class = "edit", how can I tailor it to 3 classes ? – Maryam-AM Mar 12 '17 at 18:38
  • @CaptainHere can we perform ```document.getElementByClassName("edit")[0].addEventListener("click", doSomething);``` in the same manner? For me it's not working. – Praneet Dixit Jun 19 '20 at 12:29
  • 1
    @PraneetDixit It should be `getElementsByClassName` – CaptainHere Jun 20 '20 at 13:07

0 Answers0