You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 2-ui/1-document/06-dom-attributes-and-properties/article.md
+91-90Lines changed: 91 additions & 90 deletions
Original file line number
Diff line number
Diff line change
@@ -87,16 +87,16 @@ Então, se um atributo não é padrão, não há uma propriedade DOM para ele. H
87
87
88
88
Claro. Todos atributos são acessíveis usando os seguintes métodos:
89
89
90
-
-`elem.hasAttribute(name)` -- checa a existencia.
90
+
-`elem.hasAttribute(name)` -- checa a existencia do valor.
91
91
-`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.
94
94
95
-
These methods operate exactly with what's written in HTML.
95
+
Esses métodos operam exatamente com o que está escrito no HTML.
96
96
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`.
98
98
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:
100
100
101
101
```html run
102
102
<bodysomething="non-standard">
@@ -108,42 +108,43 @@ Here's a demo of reading a non-standard property:
108
108
</body>
109
109
```
110
110
111
-
HTML attributes have the following features:
111
+
Atributos HTML tem as seguintes características:
112
112
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.
115
115
116
-
Here's an extended demo of working with attributes:
116
+
Aqui está uma demonstração estendida de como trabalhar com atributos:
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)
128
128
129
-
for (let attr ofelem.attributes) { // (4) list all
129
+
for (let attr ofelem.attributes) { // (4) lista todos
130
130
alert( `${attr.name} = ${attr.value}` );
131
131
}
132
132
</script>
133
133
</body>
134
134
```
135
135
136
-
Please note:
136
+
Observe:
137
137
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`.
142
142
143
-
## Property-attribute synchronization
143
+
## Sincronização entre propriedade e atributo
144
144
145
-
When a standard attribute changes, the corresponding property is auto-updated, and (with some exceptions) viceversa.
145
+
Quando um campo padrão muda, a propriedade correspondente é automaticamente atualizada, e (com algumas exceções) vice-versa.
146
146
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:
147
148
In the example below `id` is modified as an attribute, and we can see the property changed too. And then the same backwards:
148
149
149
150
```html run
@@ -152,56 +153,56 @@ In the example below `id` is modified as an attribute, and we can see the proper
152
153
<script>
153
154
let input =document.querySelector('input');
154
155
155
-
//attribute => property
156
+
//atributo => propriedade
156
157
input.setAttribute('id', 'id');
157
-
alert(input.id); // id (updated)
158
+
alert(input.id); // id (atualizado)
158
159
159
-
//property => attribute
160
+
//propriedade => atributo
160
161
input.id='newId';
161
-
alert(input.getAttribute('id')); // newId (updated)
162
+
alert(input.getAttribute('id')); // newId (atualizado)
162
163
</script>
163
164
```
164
165
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:
166
167
167
168
```html run
168
169
<input>
169
170
170
171
<script>
171
172
let input =document.querySelector('input');
172
173
173
-
//attribute => property
174
+
//atributo => propriedade
174
175
input.setAttribute('value', 'text');
175
176
alert(input.value); // text
176
177
177
178
*!*
178
-
//NOT property => attribute
179
+
//NÃO propriedade => atributo
179
180
input.value='newValue';
180
-
alert(input.getAttribute('value')); // text (not updated!)
181
+
alert(input.getAttribute('value')); // text (não atualizado!)
181
182
*/!*
182
183
</script>
183
184
```
184
185
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.
188
189
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.
190
191
191
-
## DOM properties are typed
192
+
## Propriedades DOM são tipadas
192
193
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:
194
195
195
196
```html run
196
197
<inputid="input"type="checkbox"checked> checkbox
197
198
198
199
<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
201
202
</script>
202
203
```
203
204
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:
@@ -216,62 +217,61 @@ There are other examples. The `style` attribute is a string, but the `style` pro
216
217
</script>
217
218
```
218
219
219
-
Most properties are strings though.
220
+
No entanto, a maioria das propriedades são strings.
220
221
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`.
222
223
223
-
Here's an example:
224
+
Aqui há um exemplo:
224
225
225
226
```html height=30 run
226
227
<aid="a"href="#hello">link</a>
227
228
<script>
228
-
//attribute
229
+
//atributo
229
230
alert(a.getAttribute('href')); // #hello
230
231
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
233
234
</script>
234
235
```
235
236
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`.
237
238
239
+
## Atributos não padronizados, dataset
238
240
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?
240
242
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.
242
244
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:
246
246
247
247
```html run
248
-
<!--mark the div to show "name" here -->
248
+
<!--marca a div para mostra "name" aqui-->
249
249
<div*!*show-info="name"*/!*></div>
250
250
<!-- and age here -->
251
251
<div*!*show-info="age"*/!*></div>
252
252
253
253
<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
255
255
let user = {
256
256
name:"Pete",
257
257
age:25
258
258
};
259
259
260
260
for(let div ofdocument.querySelectorAll('[show-info]')) {
261
-
//insert the corresponding info into the field
261
+
//insere a informação correspondente no campo
262
262
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"
264
264
}
265
265
</script>
266
266
```
267
267
268
-
Also they can be used to style an element.
268
+
Eles também podem ser usado para estilizar um elemento:
269
269
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:
271
271
272
272
```html run
273
273
<style>
274
-
/*styles rely on the custom attribute "order-state" */
274
+
/*Estilo depende do atributo customizado "order-state" */
275
275
.order[order-state="new"] {
276
276
color: green;
277
277
}
@@ -286,36 +286,37 @@ For instance, here for the order state the attribute `order-state` is used:
286
286
</style>
287
287
288
288
<divclass="order"order-state="new">
289
-
A new order.
289
+
Um pedido novo.
290
290
</div>
291
291
292
292
<divclass="order"order-state="pending">
293
-
A pending order.
293
+
Um pedido pendente.
294
294
</div>
295
295
296
296
<divclass="order"order-state="canceled">
297
-
A canceled order.
297
+
Um pedido cancelado.
298
298
</div>
299
299
```
300
300
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`?
302
302
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:
304
304
305
305
```js
306
-
//a bit simpler than removing old/adding a new class
306
+
//um pouco mais simples que remover classes antigas/adicionar classes novas.
307
307
div.setAttribute('order-state', 'canceled');
308
308
```
309
309
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.
311
311
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).
313
313
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`.
315
315
316
+
Por exemplo, se um `elem` tiver um atributo chamado `"data-about"`, estará disponível em `elem.dataset.about`.
316
317
For instance, if an `elem` has an attribute named `"data-about"`, it's available as `elem.dataset.about`.
317
318
318
-
Like this:
319
+
Bem assim:
319
320
320
321
```html run
321
322
<bodydata-about="Elephants">
@@ -324,9 +325,9 @@ Like this:
324
325
</script>
325
326
```
326
327
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`.
328
329
329
-
Here's a rewritten "order state" example:
330
+
Aqui vai um exemplo "estado do pedido" reescrito:
330
331
331
332
```html run
332
333
<style>
@@ -344,43 +345,43 @@ Here's a rewritten "order state" example:
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.
360
361
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.
362
363
363
364
## Summary
364
365
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.
367
368
368
-
A small comparison:
369
+
Uma pequena comparação:
369
370
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|
| 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|
374
375
375
-
Methods to work with attributes are:
376
+
Métodos para trabalhar com atributos são:
376
377
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.
382
383
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:
384
385
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