JacobWilliamRoy
JacobWilliamRoy

Reputation: 11

Why does Microsoft Edge reorder html attributes before rendering a page?

So I wrote some Javascript that scrolls to a place on the document when the user clicks on a button:

document.getElementById("navContact").addEventListener("click", scrollToSection);

function scrollToSection() {
    /* this = element on which the user clicked */
    smoothScroll(this.attributes[0].value.split("#")[1]);
}

It's nice, simple, easy to read and debug. The only issue is that it gets the name of the section to which it must scroll by reading it from a named node map. In my markup, the attributes are ordered like so:

<a href="#contact_us" id="navContact"></a> 
<--! document.getElementById("navContact").attributes = [href="contact_us", id="navContact"] -->

But when I check this in Edge's DOM explorer, the attributes are reordered:

<a id="navContact" href="#contact_us"></a>
<--! document.getElementById("navContact").attributes = [id="navContact", href="contact_us"] -->

As per Josiah Keller's suggestion I'm changing the js to use element.getAttribute() instead of this.attributes.

In the meantime, I'm dying to know, why does Edge do this?

Upvotes: 1

Views: 177

Answers (2)

jmargolisvt
jmargolisvt

Reputation: 6088

.attributes returns a NamedNodeMap. According to MDN:

The NamedNodeMap interface represents a collection of Attr objects. Objects inside a NamedNodeMap are not in any particular order, unlike NodeList, although they may be accessed by an index as in an array.

While you can reference it with this.attributes[0], you'll notice that you can't push to it because it's not an array. It's an object, it's constructed without order in mind, and so it's probably not a bug in Edge. It's still returning what it's supposed to, which is an unordered object.

As others are suggesting, you should just get the href specifically, but hopefully this sheds some light on why it's not working as you might think.

Upvotes: 4

Jon W&#229;lstedt
Jon W&#229;lstedt

Reputation: 43

Why not use el.getAttribute('href') instead? https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

Upvotes: 2

Related Questions