Skip to content

Commit 1ccbb5f

Browse files
committed
[LES-17.2/st-compl] selecting-manipulating-dom-el
Practice/getting "document/DOM" el's. Using "querySelector/All()" etc. Worth noting: - both the lesson material and additional practice. FS-dev: B-3 / JS basic
1 parent ed101d1 commit 1ccbb5f

File tree

7 files changed

+637
-0
lines changed

7 files changed

+637
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
7+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
8+
<title>DOM</title>
9+
<link rel="stylesheet" href="./styles.css">
10+
<script src="./index.js" defer></script>
11+
</head>
12+
13+
<body style="background-color: #1c1b21; text-align: center">
14+
<img src="./logo.svg" alt>
15+
<div class="panel">I love this!</div>
16+
<input class="input" id="input">
17+
<button class="button">Change</button>
18+
</body>
19+
20+
</html>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
3+
console.log(document);
4+
/*
5+
#document
6+
<!DOCTYPE html>
7+
<html lang="en">
8+
<head>
9+
<meta charset="UTF-8">
10+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
11+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
12+
<title>DOM</title>
13+
<link rel="stylesheet" href="./styles.css">
14+
<script src="./index.js" defer></script>
15+
</head>
16+
<body style="background-color: #1c1b21; text-align: center">
17+
<img src="./logo.svg" alt>
18+
<div class="panel">I love this!</div>
19+
<input class="input" id="input">
20+
<button class="button">Change</button>
21+
</body>
22+
</html>
23+
*/
24+
25+
console.log(document.querySelector('.panel')); // <div class="panel">I love this!</div>
26+
27+
const panelText = document.querySelector('.panel').innerText;
28+
console.log(panelText); // I love this!
29+
30+
const panel = document.querySelector('.panel');
31+
panel.textContent = 'I hate this..';
32+
console.log(panel.textContent); // I hate this..
33+
34+
const input = document.querySelector('.input');
35+
console.log(input.value); // ...
36+
input.value = 'enter..';
37+
console.log(input.value); // enter..
Lines changed: 25 additions & 0 deletions
Loading
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>DOM - practice</title>
8+
<script src="./index.js" defer></script>
9+
</head>
10+
11+
<body>
12+
<div id="profile-card">
13+
<h2>Имя пользователя: <span id="user-name">...</span></h2>
14+
<p>Статус: <span id="user-status">...</span></p>
15+
</div>
16+
17+
<div>
18+
<label for="password-input">Пароль:</label>
19+
<input id="password-input" type="text" value="qwerty">
20+
<p id="validation-message"></p>
21+
</div>
22+
</body>
23+
24+
<ul id="item-list">
25+
<li>Молоко</li>
26+
<li class="new-item">Хлеб</li>
27+
<li>Сыр</li>
28+
<li class="new-item">Сок</li>
29+
</ul>
30+
31+
</html>
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
'use strict';
2+
3+
// Задание 1:
4+
// Представь, что у тебя есть вот такая HTML-структура для карточки профиля:
5+
// <div id="profile-card">
6+
// <h2>Имя пользователя: <span id="user-name">...</span></h2>
7+
// <p>Статус: <span id="user-status">...</span></p>
8+
// </div>
9+
// А в твоем JavaScript-коде есть объект с данными, которые пришли, скажем, с сервера:
10+
// const userData = {
11+
// name: 'Елена',
12+
// status: 'в сети'
13+
// };
14+
// Твоя задача: Напиши JS-код, который:
15+
// 1. Найден нужные <span> элементы по их id.
16+
// 2. Вставит в них имя и статус из объекта userData.
17+
// В результате на странице вместо "..." должны появиться "Елена" и "в сети".
18+
19+
const userData = {
20+
name: 'Елена',
21+
status: 'в сети',
22+
};
23+
24+
const userName = document.querySelector('#user-name');
25+
const userStatus = document.querySelector('#user-status');
26+
27+
userName.textContent = userData.name;
28+
userStatus.textContent = userData.status;
29+
30+
/*
31+
Имя пользователя: Елена
32+
Статус: в сети
33+
*/
34+
35+
// Задание 2:
36+
// На странице есть форма для ввода пароля. Изначально в поле уже есть какое-то значение.
37+
// <div>
38+
// <label for="password-input">Пароль:</label>
39+
// <input id="password-input" type="text" value="qwerty">
40+
// <p id="validation-message"></p>
41+
//</div>
42+
// Твоя задача: Написать JS-код, который проверяет пароль при загрузке страницы.
43+
// 1. Получи элемент поля ввода и элемент параграфа для сообщения.
44+
// 2. Считай значение (текст) из поля ввода.
45+
// 3. Проверь его длину.
46+
// 4. Если длина пароля меньше 8 символов, то в параграф #validation-message нужно вывести сообщение "Пароль слишком короткий" и покрасить этот текст в красный цвет.
47+
// 5. В противном случае — вывести "Надежный пароль" зелёного цвета.
48+
// Подсказка: Чтобы изменить цвет текста элемента, можно использовать его свойство .style.color. Например: element.style.color = 'red';.
49+
50+
function checkPassword() {
51+
const passwordInput = document.querySelector('#password-input');
52+
const validMessage = document.querySelector('#validation-message');
53+
const inputValue = passwordInput.value;
54+
55+
if (!inputValue) {
56+
return false;
57+
}
58+
59+
if (inputValue.length < 8) {
60+
validMessage.textContent = 'Пароль слишком короткий';
61+
validMessage.style.color = 'red';
62+
return false;
63+
} else {
64+
validMessage.textContent = 'Надежный пароль';
65+
validMessage.style.color = 'green';
66+
return true;
67+
}
68+
}
69+
70+
checkPassword(); // qwerty - Пароль слишком короткий
71+
72+
// Задание 3:
73+
// У тебя есть список элементов на странице. Некоторые из них помечены как "новые" с помощью специального класса.
74+
// <ul id="item-list">
75+
// <li>Молоко</li>
76+
// <li class="new-item">Хлеб</li>
77+
// <li>Сыр</li>
78+
// <li class="new-item">Сок</li>
79+
// </ul>
80+
// Твоя задача: Написать JS-код, который "обработает" все новые элементы.
81+
// 1. Найди все элементы с классом new-item.
82+
// 2. Используя цикл, перебери найденные элементы.
83+
// 3. Для каждого из них сделай две вещи:
84+
// - Добавь в конец их текста пометку "(новинка!)".
85+
// - Сделай их текст жирным.
86+
// Подсказка: Чтобы сделать текст жирным, можно использовать свойство .style.fontWeight = 'bold';. Чтобы добавить текст в конец, можно использовать конструкцию element.textContent = element.textContent + ' какой-то текст'; или более короткую element.textContent += ' какой-то текст';.
87+
88+
function getNewItems() {
89+
const itemsList = document.querySelectorAll('li');
90+
91+
if (itemsList.length < 1) {
92+
return false;
93+
}
94+
95+
itemsList.forEach((item) => {
96+
if (item.classList.contains('new-item')) {
97+
item.style.fontWeight = 'bold';
98+
item.textContent += ' (новинка!)';
99+
}
100+
});
101+
}
102+
103+
// getNewItems();
104+
105+
// ?? альтернативное решение
106+
// Сразу находим только то, что нам нужно
107+
const newItems = document.querySelectorAll('.new-item');
108+
109+
// Теперь не нужна проверка if, ведь в newItems УЖЕ лежат только нужные элементы
110+
newItems.forEach((item) => {
111+
item.style.fontWeight = 'bold';
112+
item.textContent += ' (новинка!)';
113+
});
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
.panel {
2+
margin-bottom: 20px;
3+
border-radius: 10px;
4+
padding: 40px;
5+
font-size: 18px;
6+
color: white;
7+
background: rgba(255, 255, 255, .05);
8+
}
9+
10+
.input {
11+
border: 1px solid rgba(212, 212, 212, .05);
12+
border-radius: 10px;
13+
padding: 15px 16px;
14+
height: 56px;
15+
box-sizing: border-box;
16+
font-size: 18px;
17+
line-height: 21px;
18+
color: white;
19+
box-shadow: none;
20+
outline: none;
21+
background: rgba(255, 255, 255, .05);
22+
}
23+
24+
.button {
25+
display: inline-flex;
26+
justify-content: center;
27+
align-items: center;
28+
border: none;
29+
border-radius: 10px;
30+
padding: 20px 40px;
31+
box-sizing: border-box;
32+
text-align: center;
33+
color: white;
34+
background: #6c38cc;
35+
cursor: pointer;
36+
transition: all .2s;
37+
}
38+
39+
.button:hover {
40+
background-color: #844fe6;
41+
}

0 commit comments

Comments
 (0)