Dseok의 실전 예제로 웹개발 한방에 끝내기

웹개발, 혼자 하려니 막막하고 힘드시죠? 저 또한 그렇습니다. 힘든 웹개발... 실전 예제를 통해 함께 공부해요!!!!😁📕

Javascript

[Dseok의 코딩스터디] includes()메서드로 검색어 필터링 기능 만들어보기

Dseok 2024. 10. 4. 17:10
반응형
SMALL

검색기능을 만들 수 있는 방법은 다양합니다.

이번에 코딩테스트에서 틀렸지만 사용해봤던 includes()메서드로 검색 필터 기능을 만들어보고자 합니다.

기본 HTML 구성은 아래와 같습니다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./css/reset.css">
  <title>search filter</title>
</head>
<body>
<!-- 구성 시작 -->
  <div class="wrap">
    <input type="text" id="searchInput" placeholder="검색어를 입력하세요" />
    <div class="todo-list" id="todoList"></div>
  </div>
<!-- 구성 끝 -->
</body>
</html>

위에 <div class="wrap">은 그냥 가운데에 놓기 위해서 적은 코드입니다.

가운데에 놓는 역할 말고는 다른 역할이 일절 없습니다.

 

다음은 그냥 넣기 너무 지져분하니 정말정말 간단한 스타일링을 해줬습니다.

@charset "utf-8";
.wrap{
  width: 1010px;
  margin: 0 auto;
  padding: 50px 0;
}
.todo-list {
  margin-top: 20px;
}

.todo-item {
  margin: 5px 0;
}

뭐 이것도 아무렇게나 가져다 쓰시면 됩니다.

 

다음은 자바스크립트 코드입니다.

핵심적인 내용입니다.

계속 연습을 해봐야하는데 많은 연습을 하지 못해 시간이 좀 걸렸습니다.

// mockData생성
const todos = [
  { id: 1, content: 'javascript 공부하기' },
  { id: 2, content: 'React 공부하기' },
  { id: 3, content: '러닝하기' },
  { id: 4, content: '과제하기' },
];

// mockData todo-list에 뿌리기
const rendedList = (todoItemList) => {
  const todoList = document.getElementById('todoList'); // DOM가져오기
  todoList.innerHTML = ''; // 초기화 한번 시키고

  todoItemList.forEach((todo) => {
    const todoItem = document.createElement('div');
    todoItem.className = 'todo-list';
    todoItem.textContent = todo.content;
    todoList.appendChild(todoItem);
  });
};

rendedList(todos); // 뿌려주기 실행

const searchInput = document.getElementById('searchInput'); // input DOM 가져오기

// 아래는 이벤트 실행하기
searchInput.addEventListener('input', () => {
  const inputValue = searchInput.value.toLowerCase();
  const filterTodos = todos.filter((todo) => todo.content.toLowerCase().includes(inputValue)); // 여기에 inlcudes()메서드가 쓰임.
  rendedList(filterTodos);
});

 

위 코드에서 toLowerCase()를 사용한 이유는 검색을 할 때 대소문자를 신경 안쓰고 검색을 할 수 있게 하기 위해서 입니다.

즉, 소문자로만 검색을 해도 대소문자 상관없이 검색어가 필터링 됩니다.

 

includes()메서드를 사용하고자 작업을 했는데 기타 다른 메서드들도 보이네요!

다른 메서드들은 다음에 정리해보고자 합니다.

여기서 보이는 메서드들은 createElement(), appendChild(), toLowerCase(), filter() 정도가 있겠네요.

createElement()메서드와 toLowerCase()메서드는 간단한 메서드라 정리를 안할겁니다.

 

다음은 전체 코드입니다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./css/reset.css">
  <title>search filter</title>
  <style>
    @charset "utf-8";
    .wrap{
      width: 1010px;
      margin: 0 auto;
      padding: 50px 0;
    }
    .todo-list {
      margin-top: 20px;
    }

    .todo-item {
      margin: 5px 0;
    }
  </style>
</head>
<body>
  <div class="wrap">
    <input type="text" id="searchInput" placeholder="검색어를 입력하세요" />
    <div class="todo-list" id="todoList"></div>
  </div>
  <script>
    // mockData생성
    const todos = [
      { id: 1, content: 'javascript 공부하기' },
      { id: 2, content: 'React 공부하기' },
      { id: 3, content: '러닝하기' },
      { id: 4, content: '과제하기' },
    ];

    // mockData todo-list에 뿌리기
    const rendedList = (todoItemList) => {
      const todoList = document.getElementById('todoList'); // DOM가져오기
      todoList.innerHTML = ''; // 초기화 한번 시키고

      todoItemList.forEach((todo) => {
        const todoItem = document.createElement('div');
        todoItem.className = 'todo-list';
        todoItem.textContent = todo.content;
        todoList.appendChild(todoItem);
      });
    };

    rendedList(todos); // 뿌려주기 실행

    const searchInput = document.getElementById('searchInput'); // input DOM 가져오기

    searchInput.addEventListener('input', () => {
      const inputValue = searchInput.value.toLowerCase();
      const filterTodos = todos.filter((todo) => todo.content.toLowerCase().includes(inputValue)); // 여기에 inlcudes()메서드가 쓰임.
      rendedList(filterTodos);
    });

  </script>
</body>
</html>

 

 

저는 원래 파일을 분리해서 작업을 합니다.

그러면 복사붙혀넣기 하기 불편하니 블로그에서는 한 파일안에 넣어봤습니다.

제가 파일을 분리해서 작업하는 방법이 궁금하시다면 아래 제 깃허브 주소로 들어와서 한번 보시면 좋을 것 같습니다.

 

https://github.com/Dseok12/MacLocal/tree/main/javascript/Vanilla/Study/SearchFilter/search_filter

반응형
LIST