On 11.01.2024 19:36, Jukka K. Korpela wrote:
> Janis Papanagnou wrote:
>
>> So I also assume from that that we can't just change the single
>> CSS style attribute definition by Javascript to change all the
>> <img> elements,
>
> We can. It's just not practical as a rule.
The motivation for my question was that I naturally use a CSS style
definition to avoid specifying the specific attributes with every
single <img> individual attributes. My hope way that this simple
segregation of duties between CSS and HTML could be also reflected
in case of changes done through Javascript.
>
>> and that this iteration over all <img>es is
>> unavoidable,
>
> Applying something to all img elements is essentially iterative anyway,
> though the iterative process can be hidden syntactically.
Indeed I have not expected that the many attribute changes would
magically vanish, but that it's done implicitly by the browser's
rendering engine. If I switch to explicit DOM manipulations (with
the Javascript loop) this gets then explicit by the JS application.
In other words, I would have found it conceptionally cleaner, and
I could also have imagined that it might be a bit more performant
to let the rendering engine do the task (the loop) implicitly.
So far my thoughts.
>
>> probably because the <style> elements are just
>> accessed once before building the DOM, and only in the DOM we
>> can change the attribute values? - Is that assumption correct?
>
> It seems that changing the content of a <style> element with client-side
> JavaScript changes the rendering. I haven’t checked what the “HTML
> standard” says about it. Anyway, it’s clumsier. In JS, you can access
> the <style> element as text, but there are no built−in tools for
> operating on it structurally.
>
> A very trivial example, based on the assumption that you just want to
> replace the contents of the first <style> element with something else:
>
> function chg() {
> document.getElementsByTagName('style')[0].innerHTML =
> 'img { max-width: 100px; }';
> }
Yes, this is indeed quite an ugly construct. My hope was that the
attribute can be changed with cleaner syntax (as opposed to defining
a complete new string as innerHTML).
So if that's the other choice, I also prefer the explicit JS loop.
I'll stay with your previously suggested method.
The complete application (to toggle the image sizes) became
<script>
var w = [ 50, 75, 100 ];
var h = [ 30, 45, 60 ];
var size = 0;
function switch_size() {
const images = document.querySelectorAll('img');
size = (size+1)%3;
images.forEach((image) => {
image.style.maxWidth = w[size];
image.style.maxHeight = h[size];
})
}
</script>
Thanks for the insights and additional explanations that you provided!
Janis