On Friday, July 2, 2021 at 6:56:58 PM UTC+2 Mat wrote:

> In HTML one can apply an ID attribute to objects. I know this is not 
> possible in TW... but I don't get why. Can someone explain why this is not 
> possible or not appropriate, please.


Hi Mat, 

It is possible to use IDs with TW. ... BUT it won't be reliable. ... 

HTML element IDs are per definition unique. But with TW can't guarantee 
this uniqueness  since we have transclusions. So in the TW story-river it 
can happen that an ID is visible 2 or more times. 

The CSS definitions will most likely work. BUT depending on the browser 
implementation we can not guarantee a consistent behaviour for all 
elements. 

Have a look at this jsFiddle: https://jsfiddle.net/fLcdq7ut/17/  

The HTML code is like this:

<html>
<head>
  <title>getElementById example</title>
</head>
<body>
  <p id="para">Some ID text here</p>
  <p class="para">Some classed text here</p>

  <button onclick="changeColor('blue');">blue</button>
  <button onclick="changeColor('red');">red</button>
  
  <p id="para">Some ID text here</p>
  <p class="para">Some classed text here</p></body>
</html>

The JS code is like this: 

function changeColor(newColor) {
  var elem = document.getElementById('para');
  elem.style.color = newColor;
  
  var elements = document.getElementsByClassName('para');
  for (var i=0; i<elements.length; i++) {
      elements[i].style.color = newColor;
  }
}

If you click the buttons you see, that the ID elements are not updated 
both. It's only the first one, since the function document.getElementById() 
assumes there is only 1 of them. ... By definition it will return the first 
element it finds in the DOM tree. 

document.getElementsByClassName() knows there can be many elements with the 
same class name and it will return an array, so we can use a loop to define 
the new color. 

This is only a fast example, to show the differences in a way that should 
be understandable. .. It would be possible to add a class to the IDs too, 
to get them with the class name. ... BUT this would only solve this 
particular usecase. 

The browser assumes there is only 1 ID active at a time. So we just don't 
know, what happens internally. We can't reliably guarantee that everything 
works as expected. 

hope that helps
mario

-- 
You received this message because you are subscribed to the Google Groups 
"TiddlyWiki" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to tiddlywiki+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/tiddlywiki/540e0f00-db45-45c0-b388-75521a576cc1n%40googlegroups.com.

Reply via email to