3

In the following PHP code DOMDocument::getElementById returns the node <a name="test">instead of the node <div id="test">:

<?php
$doc = new DOMDocument();
$doc->loadHTML('<a name="test"></a><div id="test"></div>'); // triggers duplicate ID warning
echo $doc->getElementById("test")->nodeName; // outputs "a"
?>

This happens only for <a>nodes. Is this intended?

JavaScript handles it as I expected:

<script>
window.addEventListener('DOMContentLoaded', function() {
    document.body.innerHTML = '<a name="test"></a><div id="test"></div>';
    console.log(document.getElementById('test'));
});
</script>

EDIT (question was marked as duplicate): This question is not about wether I should use name or id and also not about using both name and id, but why PHP finds nodes with name attribute when I search for an id.

Toxiro
  • 528
  • 1
  • 3
  • 12

3 Answers3

1

As of HTML5, the name attribute isn't supported in a tags so it looks like it's changed to an id attribute.

joelrosenthal
  • 471
  • 4
  • 10
  • The page I am trying parse is XHTML 1.0, but I guess you are right and PHP does not really care about the Doctype. – Toxiro Feb 22 '18 at 20:52
1

This is most likely a hold-over from PHP emulating old IE behaviour. In IE 7 and earlier, document.getElementById() did indeed treat name attributes on <a> elements as if they were id attributes and so would match the <a> element rather than the <div> element. IE has long since moved on, but PHP it seems, on this point, has not.

Alohci
  • 78,296
  • 16
  • 112
  • 156
0

As you can read here

For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is.

Parse the URL, and let fragid be the component of the URL. If fragid is the empty string, then the indicated part of the document is the top of the document. If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here. If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here. Otherwise, there is no indicated part of the document.

When I pasted your code to PHP sandbox I noticed an interesting warning: enter image description here

Community
  • 1
  • 1
Krzysztof Raciniewski
  • 4,735
  • 3
  • 21
  • 42