Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:target selector on dynamic generated element not affect

My test shows that the :target selector effect on elements who exist in the DOM when page loaded only. Am I right?

I can't create a snippet here because I can't call the iframe's snippet with hash (#) so you can see the issue here:

http://output.jsbin.com/vixave#new_element

HTML Button

<button onclick="addElement()">Add element</button>

CSS

div:target {
  background:red;
  color:#fff;
}

Javascript

function addElement() {
  document.body.innerHTML += '<div id="new_element">New element</div><br /><a href="#new_element">highlight</a>';  
}

In this demo you can see that after you click on the button and the div #new_element added to the body, he doesn't "get" the style. Only when you click on the link which call again to the same URL, the style will be apply.

Update

Further @BoltClock♦'s comment, this happens in Chrome and FireFox but in IE (SO strange) it's working as expected.

like image 970
Mosh Feu Avatar asked Oct 18 '22 09:10

Mosh Feu


1 Answers

Applying styles of :target selectors when a fragment (the string after a # in an URL) is present is the correct behaviour.

The specified behaviour can be found in the W3C Selectors and HTML5 specifications.

6.6.2. The target pseudo-class :target

Some URIs refer to a location within a resource. This kind of URI ends with a "number sign" (#) followed by an anchor identifier (called the fragment identifier).

URIs with fragment identifiers link to a certain element within the document, known as the target element. For instance, here is a URI pointing to an anchor named section_2 in an HTML document:

http://example.com/html/top.html#section_2

A target element can be represented by the :target pseudo-class. If the document's URI has no fragment identifier, then the document has no target element.

https://www.w3.org/TR/selectors/#target-pseudo

When the document loads and there's no valid name or id attribute according to the below alogorithm, the document has no valid fragment identifier.

5.6.9 Navigating to a fragment identifier

...

  1. If there is an element in the DOM that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  2. No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.

https://www.w3.org/TR/html5/browsers.html#scroll-to-fragid

However, it seems to be unspecified how vendors should deal with inserted nodes with an id or name attribute that equals to the URL fragment (that would make a valid fragment identifier while loading/navigating the document).

like image 50
try-catch-finally Avatar answered Oct 28 '22 15:10

try-catch-finally