Search code examples
phpdomdomdocumentgetelementbyid

PHP returns element with name instead of ID


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.


Solution

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