DEV Community

Discussion on: How To: Build A Simple Search Bar in JavaScript

Collapse
 
jdboris profile image
Joe Boris • Edited

EDIT: Edited to sound nicer

Good article. Here are some tips...

You should define the list variable manually. You technically don't need to, because of a little-known feature that automatically defines a global variable for each HTML element with an ID, but it's a bad practice to rely on that.

It looks like you may have made a mistake in the section where you introduce clearList. Your example code still has the placeholder comment for step 4 instead of calling setList.

Your clearList function is overcomplicated. You can just use list.innerHTML = "".

Try to follow more standard conventions and patterns. Instead of setList, I would name it renderList since showing data on the page is referred to as rendering.

Checking the length of the textbox value is unnecessary, because an empty string is already falsy. if( value.trim() ) is sufficient.

I prefer to use append rather than appendChild since it's shorter.

Lastly, you can't go wrong with document.createElement, but I prefer to use innerHTML when possible since it's shorter. You just have to remember that it clears event listeners on children.

Collapse
 
am20dipi profile image
Adriana DiPietro

I appreciate the feedback, but there are ways of providing "criticism" as you claim without condescension. Yes -- there are many ways to achieve a goal with code -- we all know that. This is a beginner's ~guide~... guide meaning do things the way you would like and follow my outline to your desired effect. It's nice to see that we all can think and improve on others; but try to say it nicer. Also "shorter" does not equate to better. Sometimes "longer" improves readability, especially for beginners. Nonetheless, I appreciate you taking the time to read and comment on my post. I like continuing the conversation past the post :)

Collapse
 
travissanon profile image
Travis Sanon • Edited

I'd say that

function clearList() {
  list.innerHTML = ''
}
Enter fullscreen mode Exit fullscreen mode

Is easier to read than

function clearList() {
    while (list.firstChild){
        list.removeChild(list.firstChild)
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
zippcodder profile image
Deon Rich

I agree. Good article, great project for people still starting out.

Thread Thread
 
am20dipi profile image
Adriana DiPietro

Thank you Deon!

Collapse
 
alexfstack profile image
Alex-FStack • Edited

Boris made some great points on how to improve the code, did not see anything 'condescending' in there, all positive criticism and helpful quality tips, seems you cant take any... attitude problem?