From 1d9c8df17b90f8dfbf6cbfe49cfd0acbb78c9a14 Mon Sep 17 00:00:00 2001 From: Alexander Popov Date: Sun, 12 Mar 2023 00:11:13 +0300 Subject: [PATCH] array from html children --- .../2023/javascript/foreach-html-children.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 content/posts/2023/javascript/foreach-html-children.md diff --git a/content/posts/2023/javascript/foreach-html-children.md b/content/posts/2023/javascript/foreach-html-children.md new file mode 100644 index 0000000..49638cc --- /dev/null +++ b/content/posts/2023/javascript/foreach-html-children.md @@ -0,0 +1,35 @@ +--- +title: "πŸ‘ΆπŸ» ΠŸΠ΅Ρ€Π΅Π±ΠΎΡ€ ΠΏΠΎΡ‚ΠΎΠΌΠΊΠΎΠ² HTML элСмСнта" +date: 2023-03-12T00:10:00+03:00 +draft: false +tags: [tips, javascript] +--- + +## ΠŸΠ΅Ρ€Π΅Π±ΠΎΡ€ ΠΏΠΎΡ‚ΠΎΠΌΠΊΠΎΠ² HTML элСмСнта + +ΠŸΡ€ΠΎΡΡ‚ΠΎ Ρ‚Π°ΠΊ ΠΏΡ€ΠΈΠΌΠ΅Π½ΠΈΡ‚ΡŒ ΠΌΠ΅Ρ‚ΠΎΠ΄ `forEach` ΠΊ Π°Ρ‚Ρ€ΠΈΠ±ΡƒΡ‚Ρƒ `.children` +HTML элСмСнта Π½Π΅ получится. +Для Π½Π°Ρ‡Π°Π»Π° Π½Π΅ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌΠΎ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Ρ‚ΡŒ Π°Ρ‚Ρ€ΠΈΠ±ΡƒΡ‚ Π² массив. + +ΠŸΡ€Π΅Π΄ΠΏΠΎΠ»ΠΎΠΆΠΈΠΌ, Ρ‡Ρ‚ΠΎ `pageContent` β€” это `div` с Π½Π΅ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΌΠΈ ΠΎΠ΄Π½ΠΎΡ‚ΠΈΠΏΠ½Ρ‹ΠΌΠΈ элСмСнтами, +ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ Π½ΡƒΠΆΠ½ΠΎ ΠΏΠ΅Ρ€Π΅Π±Ρ€Π°Ρ‚ΡŒ ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΎΠΌ `forEach`. + +```javascript +let pageContent = document.getElementById('page-content'); +``` + +Π’ΠΎΡ‚ нСсколько ΠΏΡ€ΠΈΠΌΠ΅Ρ€ΠΎΠ², ΠΊΠ°ΠΊ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Ρ‚ΡŒ Π°Ρ‚Ρ€ΠΈΠ±ΡƒΡ‚ +`pageContent.children` Π² массив. + +```javascript +let pageContentChildren = [...pageContent.children]; +// ΠΈΠ»ΠΈ +let pageContentChildren = [].slice.call(pageContent.children); +``` + +Π’ **ECMAScript 6** Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΎ Π½ΠΎΠ²ΠΎΠ΅ API, Π° ΠΈΠΌΠ΅Π½Π½ΠΎ ΠΌΠ΅Ρ‚ΠΎΠ΄ `.from` +для создания массивов ΠΈΠ· ΠΈΡ‚Π΅Ρ€ΠΈΡ€ΡƒΠ΅ΠΌΡ‹Ρ… ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ΠΎΠ². + +```javascript +let pageContentChildren = Array.from(pageContent.children.children); +```