From 5ef1b92e8b8dec4b3e5c6a3ee4c2e98e493631fb Mon Sep 17 00:00:00 2001 From: Ilya Kantor Date: Mon, 13 Feb 2017 23:38:52 +0300 Subject: [PATCH] up --- .../1-get-user-attribute/solution.md | 19 - .../solution.view/index.html | 14 - .../1-get-user-attribute/task.md | 25 - .../2-set-class-links/solution.md | 52 -- .../article.md | 545 ------------------ .../1-get-user-attribute/solution.md | 20 + .../1-get-user-attribute/task.md | 21 + .../2-set-class-links/solution.md | 36 ++ .../solution.view/index.html | 16 +- .../2-set-class-links/task.md | 13 +- .../9-attributes-and-properties/article.md | 438 ++++++++++++++ 11 files changed, 527 insertions(+), 672 deletions(-) delete mode 100644 2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.md delete mode 100644 2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.view/index.html delete mode 100644 2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/task.md delete mode 100644 2-ui/1-document/9-attributes-and-custom-properties/2-set-class-links/solution.md delete mode 100644 2-ui/1-document/9-attributes-and-custom-properties/article.md create mode 100644 2-ui/1-document/9-attributes-and-properties/1-get-user-attribute/solution.md create mode 100644 2-ui/1-document/9-attributes-and-properties/1-get-user-attribute/task.md create mode 100644 2-ui/1-document/9-attributes-and-properties/2-set-class-links/solution.md rename 2-ui/1-document/{9-attributes-and-custom-properties => 9-attributes-and-properties}/2-set-class-links/solution.view/index.html (69%) rename 2-ui/1-document/{9-attributes-and-custom-properties => 9-attributes-and-properties}/2-set-class-links/task.md (59%) create mode 100644 2-ui/1-document/9-attributes-and-properties/article.md diff --git a/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.md b/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.md deleted file mode 100644 index 10a8f3e4..00000000 --- a/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.md +++ /dev/null @@ -1,19 +0,0 @@ - - -```html run height=100 - - -
Выберите жанр
- - - -``` - diff --git a/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.view/index.html b/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.view/index.html deleted file mode 100644 index 1bb9eecc..00000000 --- a/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/solution.view/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - -
Выберите жанр
- - - - - - \ No newline at end of file diff --git a/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/task.md b/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/task.md deleted file mode 100644 index f3ca37f2..00000000 --- a/2-ui/1-document/9-attributes-and-custom-properties/1-get-user-attribute/task.md +++ /dev/null @@ -1,25 +0,0 @@ -importance: 5 - ---- - -# Получите пользовательский атрибут - -1. Получите `div` в переменную. -2. Получите значение атрибута `"data-widget-name"` в переменную. -3. Выведите его. - -Документ: - -```html - - -
Выберите жанр
- - - -``` - -[edit src="solution" task] - diff --git a/2-ui/1-document/9-attributes-and-custom-properties/2-set-class-links/solution.md b/2-ui/1-document/9-attributes-and-custom-properties/2-set-class-links/solution.md deleted file mode 100644 index 43030446..00000000 --- a/2-ui/1-document/9-attributes-and-custom-properties/2-set-class-links/solution.md +++ /dev/null @@ -1,52 +0,0 @@ - -Сначала можно найти ссылки, например, при помощи `document.querySelectorAll('a')`, а затем выбрать из них нужные. - -Затем определимся -- что использовать для проверки адреса ссылки: свойство `href` или атрибут `getAttribute('href')`? - -Различие между ними заключается в том, что свойство будет содержать полный путь ссылки, а атрибут -- значение, указанное в HTML. - -Если открыть страницу локально, на диске, то для `` значения будут такими: - -- `a.getAttribute('href') == "/tutorial"`. -- `a.href == "file:///tutorial"` (возможно, в пути будет также буква диска). - -Здесь нужен именно атрибут, хотя бы потому, что в свойстве все ссылки уже с хостом и протоколом, а нам надо понять, был ли протокол в `href` или нет. - -Правила определения: - -- Ссылки без `href` и без протокола `://` являются заведомо внутренними. -- Там, где протокол есть -- проверяем, начинается ли адрес с `http://internal.com`. - -Итого, код может быть таким: -```js -var links = document.querySelectorAll('a'); - -for (var i = 0; i < links.length; i++) { - - var a = links[i]; - - var href = a.getAttribute('href'); - - if (!href) continue; // нет атрибута - - if (href.indexOf('://') == -1) continue; // без протокола - - if (href.indexOf('http://internal.com') === 0) continue; // внутренняя - - a.classList.add('external'); -} -``` - -...Но, как это часто бывает, знание CSS может упростить задачу. Удобнее и эффективнее здесь -- указать проверки для `href` прямо в CSS-селекторе: - -```js -// ищем все ссылки, у которых в href есть протокол, -// но адрес начинается не с http://internal.com -var css = 'a[href*="://"]:not([href^="http://internal.com"])'; -var links = document.querySelectorAll(css); - -for (var i = 0; i < links.length; i++) { - links[i].classList.add('external'); -} -``` - diff --git a/2-ui/1-document/9-attributes-and-custom-properties/article.md b/2-ui/1-document/9-attributes-and-custom-properties/article.md deleted file mode 100644 index fce8bc96..00000000 --- a/2-ui/1-document/9-attributes-and-custom-properties/article.md +++ /dev/null @@ -1,545 +0,0 @@ -# Attributes and DOM properties - -The browser "reads" HTML text and generates DOM objects from it. For element nodes most standard HTML attributes automatically become properties of DOM objects. - -For instance, if the tag is ``, then the DOM object will have `body.id = "page"`. - -But the mapping is not one-to-one! Sometimes they are different, we'll see that soon. We should understand attributes and DOM properties relationship to feel comfortable with DOM. - -[cut] - -## Custom DOM properties - -We've already seen built-in DOM properties. But technically no one limits us. - -DOM nodes are regular Javascript objects. We can alter them if we'd like, create custom properties and methods. - -For instance, let's create a new property in `document.body`: - -```js run -document.body.myData = { - name: 'Caesar', - title: 'Imperator' -}; - -alert(document.body.myData.title); // Imperator -``` - -We can add a method as well: - -```js run -document.body.sayHi = function() { - alert(this.nodeName); -}; - -document.body.sayHi(); // BODY (the value of "this" in the method is document.body) -``` - -We can also modify built-in prototypes like `Element.prototype` and add new methods to all element nodes. - -So, DOM properties: - -- Can have any value. -- Are case-sensitive (`elem.nodeType`, not `elem.NoDeTyPe`). -- Work, because DOM nodes are objects. - -## HTML attributes - -In HTML language, tags may have attributes. When the browser reads HTML text and creates DOM objects for tags, it recognizes *known* attributes and creates DOM properties from them. - -So when an element has `id` or another standard attribute, the corresponding property gets created. But that doesn't happen if the attribute is non-standard. - -For instance: -```html run - - - -``` - -Please note that a standard attribute for one element can be unknown for another one. All standard attributes are described in the specification for the corresponding class. - -For instance, `type` is standard for `` ([HTMLInputElement](https://html.spec.whatwg.org/#htmlinputelement)), but not for `` ([HTMLBodyElement](https://html.spec.whatwg.org/#htmlbodyelement)): -```html run - - - - -``` - -So, if an attribute is non-standard, there won't be DOM-property for it. Is there a way to access such attributes? - -Sure. All attributes are accessible using following methods: - -- `elem.hasAttribute(name)` -- checks for existance. -- `elem.getAttribute(name)` -- gets the value. -- `elem.setAttribute(name, value)` -- sets the value. -- `elem.removeAttribute(name)` -- removes the attribute. - -Also one can read all attributes using `elem.attributes`. It's a collection of [Attr](https://dom.spec.whatwg.org/#attr) objects, each one with `name` and `value`. - -These methods operate exactly with what's written in HTML. - -Here's an example: - -```html run - - - -``` - -HTML attributes have following special features: - -- They are always strings. -- Their name is case-insensitive (that's HTML: `id` is same as `ID`). - -Here's the extended demo of working with attributes: - -```html run - -
- - - -``` - -Please note: - -1. `getAttribute('About')` -- the first letter is uppercase here, and in HTML it's all lowercase. But that doesn't matter: attribute names are case-insensitive. -2. We can assign anything to an attribute, but that becomes a string. So here we have `"123"` as the value. -3. All attributes including ones that we set are seen in `innerHTML`. -4. The `attributes` collection is iterable and has all attributes with `name` and `value`. - -## Attribute synchronization - -All standard DOM properties are synchronized with - - -Все стандартные свойства DOM синхронизируются с атрибутами, однако не всегда такая синхронизация происходит 1-в-1, поэтому иногда нам нужно значение именно из HTML, то есть атрибут. - -Рассмотрим несколько примеров. - -### Ссылка "как есть" из атрибута href - -Синхронизация не гарантирует одинакового значения в атрибуте и свойстве. - -Для примера, посмотрим, что произойдет с атрибутом `"href"` при изменении свойства: - -```html height=30 run -
- -``` - -Это происходит потому, что атрибут может быть любым, а свойство `href`, в соответствии со спецификацией W3C, должно быть полной ссылкой. - -Стало быть, если мы хотим именно то, что в HTML, то нужно обращаться через атрибут. - -````smart header="Есть и другие подобные атрибуты" -Кстати, есть и другие атрибуты, которые не копируются в точности. Например, DOM-свойство `input.checked` имеет логическое значение `true/false`, а HTML-атрибут `checked` -- любое строковое, важно лишь его наличие. - -Работа с `checked` через атрибут и свойство: - -```html run - - - -``` -```` - -### Исходное значение value - -Изменение некоторых свойств обновляет атрибут. Но это скорее исключение, чем правило. - -**Чаще синхронизация -- односторонняя: свойство зависит от атрибута, но не наоборот.** - -Например, при изменении свойства `input.value` атрибут `input.getAttribute('value')` не меняется: - -```html height=30 run - - - - -``` - -То есть, изменение DOM-свойства `value` на атрибут не влияет, он остаётся таким же. - -А вот изменение атрибута обновляет свойство: - -```html height=30 run - - - - -``` - -Эту особенность можно красиво использовать. - -Получается, что атрибут `input.getAttribute('value')` хранит оригинальное (исходное) значение даже после того, как пользователь заполнил поле и свойство изменилось. - -Например, можно взять изначальное значение из атрибута и сравнить со свойством, чтобы узнать, изменилось ли значение. А при необходимости и перезаписать свойство атрибутом, отменив изменения. - -## Классы в виде строки: className - -Атрибуту `"class"` соответствует свойство `className`. - -Так как слово `"class"` является зарезервированным словом в Javascript, то при проектировании DOM решили, что соответствующее свойство будет называться `className`. - -Например: - -```html run - - - -``` - -Кстати, есть и другие атрибуты, которые называются иначе, чем свойство. Например, атрибуту `for` (`