<header>
  <h2 class="title">Node: insertBefore()</h2>
  <p class="description">Вставляє вузол перед вказаним дочірнім вузлом батьківського вузла.</p>
</header>
<main>
  <div class="result">
    <div>
      <h3>Список завдань</h3>
      <ul id="taskList">
        <li>Зробити покупки</li>
        <li>Приготувати обід</li>
        <li>Почистити квартиру</li>
      </ul>
    </div>
    <div>
      <input type="text" id="newTask" placeholder="Введіть нове завдання">
      <select id="insertPosition">
        <option value="start">На початок списку</option>
        <option value="end">В кінець списку</option>
        <option value="after">Після вибраного завдання</option>
      </select>
      <button onclick="addTask()">Додати завдання</button>
    </div>
  </div>
</main>
body {
  font-size: 16px;
  line-height: 1.5;
  font-family: monospace;
}

header {
  background-color: #f1f1f1;
  margin-bottom: 25px;
  padding: 15px;
  -webkit-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  -moz-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

header h2.title {
  padding-bottom: 15px;
  border-bottom: 1px solid #999;
}

header p.description {
  font-style: italic;
  color: #222;
}

.result {
  background-color: #f8f8f8;
  padding: 15px;
  -webkit-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  -moz-box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

#taskList li {
  cursor: pointer;
}

#taskList li.selected {
  background-color: #ddd;
}
function addTask() {
  const taskList = document.getElementById('taskList');
  const newTask = document.getElementById('newTask').value.trim();
  const insertPosition = document.getElementById('insertPosition').value;

  if (newTask) {
    const li = document.createElement('li');
    li.textContent = newTask;

    if (insertPosition === 'start') {
      taskList.insertBefore(li, taskList.firstChild);
    } else if (insertPosition === 'end') {
      taskList.insertBefore(li, null);
    } else if (insertPosition === 'after') {
      const selectedTask = document.querySelector('#taskList li.selected');
      if (selectedTask) {
        taskList.insertBefore(li, selectedTask.nextSibling);
      } else {
        taskList.insertBefore(li, null);
      }
    }

    document.getElementById('newTask').value = '';
  }
}

const taskListItems = document.querySelectorAll('#taskList li');
taskListItems.forEach(item => {
  item.addEventListener('click', () => {
    taskListItems.forEach(item => item.classList.remove('selected'));
    item.classList.add('selected');
  });
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.