Hello, the problem is that I have a span with the property contentEditable="true"
so that the user can write in it, but it is added from javascript. and I would like to skip it when the browser translates the page.
I tried the following but it doesn't work for me
index.html
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HOla Mundo</title>
</head>
<body>
<script src="index.js"></script>
</body>
<style type="text/css">
body{
display: flex;
justify-content: space-around;
align-items: center;
background: white;
}
span{
background: #333770;
width: 50%;
height: 200px;
color: white;
font-size: 40px;
}
</style>
</html>
index.js
let span = document.createElement('span');
span.contentEditable = "true";
span.translate = "no";
document.body.appendChild(span)
For some reason the property translate ="no"
is changed to "yes"
when it is added to the DOM. how can I solve that?
On the one hand, the way you are doing it is not correct: Edit the line:
and add the following:
But this attribute is not supported by Chrome, Edge, Zafari, Mozilla and Opera browsers. The correct thing is to add a class "notranslate" with this the browser knows by default that this element will not be translated:
First , the translate attribute is not completely standard (it's part of the proposed HTML 5.1 specification I understand) so even though all browsers support it, its implementation may vary.
Second , an Element has properties (eg
id
,className
) and attributes. The attributes are grouped within the propertyattributes
. In particular,translate
it is not a property but an attribute . When the browser encounters the tagIt embeds it in the DOM with an attributes property which itself contains and whose value is . very crudely
translate
false
SPAN
mi_elemento
false
The fact that
"no"
it is interpreted asfalse
is a simple convention. From MDN :Without that convention, to illustrate, it wouldn't make sense for
It will be parsed as
true
, when in pure JS in the best of cases it would beundefined
.In your case, you can either declare
span.translate = false
instead ofspan.translate = "no"
, or usespan.setAttribute('translate', 'no');
(I think the latter is more future-proof).Bonus track
As with any JS object, the object returned by
document.createElement
allows you to assign extra properties to it, but those that don't make sense semantically have no influence on how the DOM is rendered. This implies thatIt does not generate an entry in the DOM with "attributeCustom" inside "attributes". BUT,
span.atributoCustom
just asdocument.getElementById('mi_elemento').atributoCustom
it does returnvalorCustom
and this is a good thing because it means you can extend the element. It is recommended, however, to use a namespace so as not to carry anything.In the HTML -> DOM flow, an arbitrary attribute does end up inside attributes and must be read with
span.getAttribute
.