title: What is the best way to check if a list item already exist before appending a new list item?
body: <p>I am creating a code to add new fruits to a list of fruits but I needed to check if the fruit already exist before adding the new one. My code is below. I know there are errors because I'm still new to javascript. So I need corrections.</p>
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
       &lt;head&gt;
           &lt;title&gt; Add new fruits &lt;/title&gt;
       &lt;/head&gt;
       &lt;body&gt;
           &lt;div&gt;
               &lt;p&gt;Enter a fruit to add to the list&lt;/p&gt;
    
               &lt;input type=&quot;text&quot; id=&quot;fruit&quot; /&gt;
               &lt;Button onclick=&quot;prependContent()&quot;&gt; Add to List &lt;/button&gt;
   
          &lt;/div&gt;
              &lt;ul id=&quot;list&quot;&gt;
              &lt;li&gt; Mangoes &lt;/li&gt;
              &lt;li&gt; Bananas &lt;/li&gt;
              &lt;li&gt; Oranges &lt;/li&gt;
          &lt;/ul&gt;
  
      &lt;script&gt;
          function prependContent() {
              var fruit = document.getElementById(&quot;fruit&quot;).value;   
              var list = document.getElementById(&quot;list&quot;);
              var listItem = list.getElementsByTagName(&quot;li&quot;); 
     
              if (fruit ==&quot;&quot;) { //validate input
                  alert(&quot;enter a fruit name&quot;);
                  return false;
              } else { //check if fruit already exist */
                  for (let i=0; i&lt;listItem.lenght; i++) {               
                  if (listItem[i]=fruit) {
                       alert(&quot;fruit already exist in the list&quot;);
                     return false;
                  } else { //add new fruit 
                      var li = document.createElement(&quot;li&quot;);
                      var textNode = document.createTextNode(fruit);       
        
     li.appendChild(textNode);
    
                
     list.prepend(li);
           }; 
       } 
     &lt;/script&gt;
  &lt;/body&gt;
  </code></pre>