Skip to content

Commit e45fa92

Browse files
committed
WIP
1 parent b1089eb commit e45fa92

File tree

1 file changed

+91
-90
lines changed
  • 2-ui/1-document/06-dom-attributes-and-properties

1 file changed

+91
-90
lines changed

2-ui/1-document/06-dom-attributes-and-properties/article.md

Lines changed: 91 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,16 @@ Então, se um atributo não é padrão, não há uma propriedade DOM para ele. H
8787

8888
Claro. Todos atributos são acessíveis usando os seguintes métodos:
8989

90-
- `elem.hasAttribute(name)` -- checa a existencia.
90+
- `elem.hasAttribute(name)` -- checa a existencia do valor.
9191
- `elem.getAttribute(name)` -- obtém o valor.
92-
- `elem.setAttribute(name, value)` -- defined um valor.
93-
- `elem.removeAttribute(name)` -- remove o atributo.
92+
- `elem.setAttribute(name, value)` -- define um valor.
93+
- `elem.removeAttribute(name)` -- remove um atributo.
9494

95-
These methods operate exactly with what's written in HTML.
95+
Esses métodos operam exatamente com o que está escrito no HTML.
9696

97-
Also one can read all attributes using `elem.attributes`: a collection of objects that belong to a built-in [Attr](https://dom.spec.whatwg.org/#attr) class, with `name` and `value` properties.
97+
É possível checar todos os atributos usando `elem.attributes`: uma coleção de objetos que pertence à classe incorporada [Attr](https://dom.spec.whatwg.org/#attr), com as propriedades `name` e `value`.
9898

99-
Here's a demo of reading a non-standard property:
99+
Aqui está uma demonstração da leitura de uma propriedade não padrão:
100100

101101
```html run
102102
<body something="non-standard">
@@ -108,42 +108,43 @@ Here's a demo of reading a non-standard property:
108108
</body>
109109
```
110110

111-
HTML attributes have the following features:
111+
Atributos HTML tem as seguintes características:
112112

113-
- Their name is case-insensitive (`id` is same as `ID`).
114-
- Their values are always strings.
113+
- Seus nomes são insensíveis à caixa alta ou baixa (`id` é o mesmo que `ID`).
114+
- Seus valores são sempre strings.
115115

116-
Here's an extended demo of working with attributes:
116+
Aqui está uma demonstração estendida de como trabalhar com atributos:
117117

118118
```html run
119119
<body>
120120
<div id="elem" about="Elephant"></div>
121121

122122
<script>
123-
alert( elem.getAttribute('About') ); // (1) 'Elephant', reading
123+
alert( elem.getAttribute('About') ); // (1) 'Elephant', lendo
124124
125-
elem.setAttribute('Test', 123); // (2), writing
125+
elem.setAttribute('Test', 123); // (2), definindo
126126
127-
alert( elem.outerHTML ); // (3), see if the attribute is in HTML (yes)
127+
alert( elem.outerHTML ); // (3), checar se o atributo está no HTML(sim)
128128
129-
for (let attr of elem.attributes) { // (4) list all
129+
for (let attr of elem.attributes) { // (4) lista todos
130130
alert( `${attr.name} = ${attr.value}` );
131131
}
132132
</script>
133133
</body>
134134
```
135135

136-
Please note:
136+
Observe:
137137

138-
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.
139-
2. We can assign anything to an attribute, but it becomes a string. So here we have `"123"` as the value.
140-
3. All attributes including ones that we set are visible in `outerHTML`.
141-
4. The `attributes` collection is iterable and has all the attributes of the element (standard and non-standard) as objects with `name` and `value` properties.
138+
1. `getAttribute('About')` -- a primeira letra aqui está em maiúsculo, e no HTML está totalmente em minúsculo. Mas isso não importa: nomes de atributos são insensíveis à caixa alta ou baixa.
139+
2. Nós podemos assinalar qualquer coisa a um atributo, mas se tornará uma string. Então aqui temos `"123"` como o valor.
140+
3. Todos os atributos, incluindo os que estão definidos, são visíveis no `outerHTML`.
141+
4. A coleção `attributes` é iterável e tem todos os atributos do elemento (padrões e não padrões) como objetos com propriedades `name` e `value`.
142142

143-
## Property-attribute synchronization
143+
## Sincronização entre propriedade e atributo
144144

145-
When a standard attribute changes, the corresponding property is auto-updated, and (with some exceptions) vice versa.
145+
Quando um campo padrão muda, a propriedade correspondente é automaticamente atualizada, e (com algumas exceções) vice-versa.
146146

147+
No exemplo abaixo `id` é modificado como um atributo, e nós podemos ver a propriedade mudada também. E o oposto também ocorre:
147148
In the example below `id` is modified as an attribute, and we can see the property changed too. And then the same backwards:
148149

149150
```html run
@@ -152,56 +153,56 @@ In the example below `id` is modified as an attribute, and we can see the proper
152153
<script>
153154
let input = document.querySelector('input');
154155
155-
// attribute => property
156+
// atributo => propriedade
156157
input.setAttribute('id', 'id');
157-
alert(input.id); // id (updated)
158+
alert(input.id); // id (atualizado)
158159
159-
// property => attribute
160+
// propriedade => atributo
160161
input.id = 'newId';
161-
alert(input.getAttribute('id')); // newId (updated)
162+
alert(input.getAttribute('id')); // newId (atualizado)
162163
</script>
163164
```
164165

165-
But there are exclusions, for instance `input.value` synchronizes only from attribute -> property, but not back:
166+
Mas há algumas exceções, por exemplo, `input.value` sincroniza a partir de atributo -> propriedade, mas o contrário não ocorre:
166167

167168
```html run
168169
<input>
169170

170171
<script>
171172
let input = document.querySelector('input');
172173
173-
// attribute => property
174+
// atributo => propriedade
174175
input.setAttribute('value', 'text');
175176
alert(input.value); // text
176177
177178
*!*
178-
// NOT property => attribute
179+
// NÃO propriedade => atributo
179180
input.value = 'newValue';
180-
alert(input.getAttribute('value')); // text (not updated!)
181+
alert(input.getAttribute('value')); // text (não atualizado!)
181182
*/!*
182183
</script>
183184
```
184185

185-
In the example above:
186-
- Changing the attribute `value` updates the property.
187-
- But the property change does not affect the attribute.
186+
No exemplo acima:
187+
- Mudando o atributo `value` atualiza a propriedade.
188+
- Mas a mudança da propriedade não afeta o atributo.
188189

189-
That "feature" may actually come in handy, because the user actions may lead to `value` changes, and then after them, if we want to recover the "original" value from HTML, it's in the attribute.
190+
Essa "característica", na verdade, pode ser útil, porque as ações do usuário podem fazer com que `value` mude, então se quisermos recuperar o valor "original" do HTML, está no atributo.
190191

191-
## DOM properties are typed
192+
## Propriedades DOM são tipadas
192193

193-
DOM properties are not always strings. For instance, the `input.checked` property (for checkboxes) is a boolean:
194+
Propriedades DOM nem sempre são strings. Por exemplo, a propriedade `input.checked` (para caixas de seleção) é um booleano:
194195

195196
```html run
196197
<input id="input" type="checkbox" checked> checkbox
197198

198199
<script>
199-
alert(input.getAttribute('checked')); // the attribute value is: empty string
200-
alert(input.checked); // the property value is: true
200+
alert(input.getAttribute('checked')); // o valor do atributo é: uma string vazia
201+
alert(input.checked); // o valor da propriedade é: true
201202
</script>
202203
```
203204

204-
There are other examples. The `style` attribute is a string, but the `style` property is an object:
205+
Há outros exemplos. O campo `style` é uma string, mas a propriedade `style` é um objeto:
205206

206207
```html run
207208
<div id="div" style="color:red;font-size:120%">Hello</div>
@@ -216,62 +217,61 @@ There are other examples. The `style` attribute is a string, but the `style` pro
216217
</script>
217218
```
218219

219-
Most properties are strings though.
220+
No entanto, a maioria das propriedades são strings.
220221

221-
Quite rarely, even if a DOM property type is a string, it may differ from the attribute. For instance, the `href` DOM property is always a *full* URL, even if the attribute contains a relative URL or just a `#hash`.
222+
Raramente, mesmo que o tipo de uma propriedade DOM seja uma string, ela pode diferir do atributo em si. Por exemplo, a propriedade `href` é sempre uma URL *completa*, mesmo que o atributo contenha uma URL relativa ou apenas um `#hash`.
222223

223-
Here's an example:
224+
Aqui há um exemplo:
224225

225226
```html height=30 run
226227
<a id="a" href="#hello">link</a>
227228
<script>
228-
// attribute
229+
// atributo
229230
alert(a.getAttribute('href')); // #hello
230231
231-
// property
232-
alert(a.href ); // full URL in the form http://site.com/page#hello
232+
// propriedade
233+
alert(a.href); // URL completa no formulário http://site.com/page#hello
233234
</script>
234235
```
235236

236-
If we need the value of `href` or any other attribute exactly as written in the HTML, we can use `getAttribute`.
237+
Se precisarmos do valor de `href` ou qualquer outro atributo exatamente como escrito no HTML, podemos usar `getAttribute`.
237238

239+
## Atributos não padronizados, dataset
238240

239-
## Non-standard attributes, dataset
241+
Quando escrevemos HTML, usamos vários atributos padrões. Mas e os atributos customizados, os não padrões? Primeiro, vamos ver se eles são úteis ou não? E para que servem?
240242

241-
When writing HTML, we use a lot of standard attributes. But what about non-standard, custom ones? First, let's see whether they are useful or not? What for?
243+
As vezes, atributos não padronizados são úteis para passar dados customizados do HTML para o JavaScript, ou para "marcar" elementos HTML para o JavaScript.
242244

243-
Sometimes non-standard attributes are used to pass custom data from HTML to JavaScript, or to "mark" HTML-elements for JavaScript.
244-
245-
Like this:
245+
Bem assim:
246246

247247
```html run
248-
<!-- mark the div to show "name" here -->
248+
<!-- marca a div para mostra "name" aqui-->
249249
<div *!*show-info="name"*/!*></div>
250250
<!-- and age here -->
251251
<div *!*show-info="age"*/!*></div>
252252

253253
<script>
254-
// the code finds an element with the mark and shows what's requested
254+
// o código encontra um elemento com a marca e mostra o que foi requisitado
255255
let user = {
256256
name: "Pete",
257257
age: 25
258258
};
259259
260260
for(let div of document.querySelectorAll('[show-info]')) {
261-
// insert the corresponding info into the field
261+
// insere a informação correspondente no campo
262262
let field = div.getAttribute('show-info');
263-
div.innerHTML = user[field]; // first Pete into "name", then 25 into "age"
263+
div.innerHTML = user[field]; // primeiro Pete em "name", então 25 em "age"
264264
}
265265
</script>
266266
```
267267

268-
Also they can be used to style an element.
268+
Eles também podem ser usado para estilizar um elemento:
269269

270-
For instance, here for the order state the attribute `order-state` is used:
270+
Por exemplo, para o estado do pedido, o atributo `order-state` é utilizado:
271271

272272
```html run
273273
<style>
274-
/* styles rely on the custom attribute "order-state" */
274+
/* Estilo depende do atributo customizado "order-state" */
275275
.order[order-state="new"] {
276276
color: green;
277277
}
@@ -286,36 +286,37 @@ For instance, here for the order state the attribute `order-state` is used:
286286
</style>
287287

288288
<div class="order" order-state="new">
289-
A new order.
289+
Um pedido novo.
290290
</div>
291291

292292
<div class="order" order-state="pending">
293-
A pending order.
293+
Um pedido pendente.
294294
</div>
295295

296296
<div class="order" order-state="canceled">
297-
A canceled order.
297+
Um pedido cancelado.
298298
</div>
299299
```
300300

301-
Why would using an attribute be preferable to having classes like `.order-state-new`, `.order-state-pending`, `.order-state-canceled`?
301+
Porque é preferível usar um atributo do que ter classes como `.order-state-new`, `.order-state-pendeing`, `.order-state-canceled`?
302302

303-
Because an attribute is more convenient to manage. The state can be changed as easy as:
303+
Porque um atributo é mais conveniente de se gerenciar. O estado pode ser mudado tão facilmente quanto:
304304

305305
```js
306-
// a bit simpler than removing old/adding a new class
306+
// um pouco mais simples que remover classes antigas/adicionar classes novas.
307307
div.setAttribute('order-state', 'canceled');
308308
```
309309

310-
But there may be a possible problem with custom attributes. What if we use a non-standard attribute for our purposes and later the standard introduces it and makes it do something? The HTML language is alive, it grows, and more attributes appear to suit the needs of developers. There may be unexpected effects in such case.
310+
Mas podem haver possíveis problemas com atributos customizados. O que acontece se usarmos um atributos não padronizado e depois ele é introduzido como um padrão funcional? A linguagem HTML é viva e está crescendo, e mais atributos aparecem para atender as necessidades dos desenvolvedores. Isso pode causar efeitos inesperados em tais casos.
311311

312-
To avoid conflicts, there exist [data-*](https://html.spec.whatwg.org/#embedding-custom-non-visible-data-with-the-data-*-attributes) attributes.
312+
Para evitar tais conflitos, existem os atributos [data-*](https://html.spec.whatwg.org/#embedding-custom-non-visible-data-with-the-data-*-attributes).
313313

314-
**All attributes starting with "data-" are reserved for programmers' use. They are available in the `dataset` property.**
314+
**Todos os atributos começando com "data-" são reservados para programadores usarem. Eles estão disponíveis na propriedade `dataset`.
315315

316+
Por exemplo, se um `elem` tiver um atributo chamado `"data-about"`, estará disponível em `elem.dataset.about`.
316317
For instance, if an `elem` has an attribute named `"data-about"`, it's available as `elem.dataset.about`.
317318

318-
Like this:
319+
Bem assim:
319320

320321
```html run
321322
<body data-about="Elephants">
@@ -324,9 +325,9 @@ Like this:
324325
</script>
325326
```
326327

327-
Multiword attributes like `data-order-state` become camel-cased: `dataset.orderState`.
328+
Atributos com várias palavras como `data-order-state` são definidas em camel case: `dataset.orderState`.
328329

329-
Here's a rewritten "order state" example:
330+
Aqui vai um exemplo "estado do pedido" reescrito:
330331

331332
```html run
332333
<style>
@@ -344,43 +345,43 @@ Here's a rewritten "order state" example:
344345
</style>
345346

346347
<div id="order" class="order" data-order-state="new">
347-
A new order.
348+
Um novo pedido.
348349
</div>
349350

350351
<script>
351-
// read
352+
// leitura
352353
alert(order.dataset.orderState); // new
353354
354-
// modify
355+
// modificação
355356
order.dataset.orderState = "pending"; // (*)
356357
</script>
357358
```
358359

359-
Using `data-*` attributes is a valid, safe way to pass custom data.
360+
Usar atributos `data-*` é uma forma válida e segura de passar dados customizados.
360361

361-
Please note that we can not only read, but also modify data-attributes. Then CSS updates the view accordingly: in the example above the last line `(*)` changes the color to blue.
362+
Observe que estamos não limitados ler, como bem podemos também modificar os dados. Então o CSS atualiza o visual de acordo: no exemplo acima, a última linha `(*)` muda a cor para azul.
362363

363364
## Summary
364365

365-
- Attributes -- is what's written in HTML.
366-
- Properties -- is what's in DOM objects.
366+
- Atributos -- é o que está escrito no HTML.
367+
- Propriedades -- é o que está escrito nos objetos DOM.
367368

368-
A small comparison:
369+
Uma pequena comparação:
369370

370-
| | Properties | Attributes |
371-
|------------|------------|------------|
372-
|Type|Any value, standard properties have types described in the spec|A string|
373-
|Name|Name is case-sensitive|Name is not case-sensitive|
371+
| | Propriedades | Atributos |
372+
|------|----------------------------------------------------------------------------------|----------------------------------------------------------------------|
373+
| Tipo | Qualquer valor, propriedades padronizadas tem o tipo descrito nas especificações | Uma string |
374+
| Nome | Nome é sensível a caixa alta ou baixa. | Nome não é sensívels a caixa alta ou baixa|
374375

375-
Methods to work with attributes are:
376+
Métodos para trabalhar com atributos são:
376377

377-
- `elem.hasAttribute(name)` -- to check for existence.
378-
- `elem.getAttribute(name)` -- to get the value.
379-
- `elem.setAttribute(name, value)` -- to set the value.
380-
- `elem.removeAttribute(name)` -- to remove the attribute.
381-
- `elem.attributes` is a collection of all attributes.
378+
- `elem.hasAttribute(name)` -- para checar a existência.
379+
- `elem.getAttribute(name)` -- para obter o valor.
380+
- `elem.setAttribute(name, value)` -- para definir o valor.
381+
- `elem.removeAttribute(name)` -- para remover o atributo.
382+
- `elem.attributes` é a coleção com todos os atributos.
382383

383-
For most situations using DOM properties is preferable. We should refer to attributes only when DOM properties do not suit us, when we need exactly attributes, for instance:
384+
Para a maioria das situações, usar propriedades DOM tem preferência. Nós devemos nos referir a atributos apenas quando propriedades DOM não são cabíveis, quando precisamos de atributos exatos, por exemplo:
384385

385-
- We need a non-standard attribute. But if it starts with `data-`, then we should use `dataset`.
386-
- We want to read the value "as written" in HTML. The value of the DOM property may be different, for instance the `href` property is always a full URL, and we may want to get the "original" value.
386+
- Quando precisamos de atributos não padronizados. Mas se começar com `data-`, então devemos usar `dataset`.
387+
- Quando precisamos ler o valor "a risca" no HTML. O valor da propriedade DOM pode ser diferente, por exemplo, o `href` é sempre uma URL completa, e nós talvez queremos o valor "original".

0 commit comments

Comments
 (0)