Element.setAtttribute vs direct assigment

At Security best practices page you can read at the top:

insert strings using safe native DOM manipulation methods: document.createElement() , Element.setAtttribute() , and Node.textContent .

Is there any adventage while using Element.setAttribute("id", "a") vs Element.id = "a"?

The point of that sentence is simply to say that in order to replace this:

document.body.innerHTML = '<div id="your_id">Hello</div>'

You need to use those three methods (although “setAtttribute” is spelled wrongly :smiley:).

But there are some advantages of setAtttribute, from what I can see in a comment in my source code:

// this can handle "data-attributes" AND read-only "width" in SVG nodes!

Other than that, I would say it doesn’t matter that much (in TypeScript there are also specific use-cases).

1 Like

Thank you for your answer, @juraj.masiar. So we have both copied over “setAtttribute” with the typo now :).

So I guess the main difference is that setAttribute is more versatile and generic.

Another difference I see is that Element.id = "a" is a direct assignment to an object’s instance variable, while Element.setAttribute("id", "a") requires an additional function call, which may result in a slight performance loss . Can someone confirm that this is true in the JavaScript context?

1 Like

Regarding the performance benefits of avoiding a function call :slight_smile:, this reminds me younger me, when I also tried to optimize code way too much :smiley:.

Note that this is not like in C/C++, where function call means break of execution flow.
JavaScript is an interpreted language, so interpreter (browser) can do many function calls even for a simple assignment. Especially when handling DOM.

I would strongly recommend writing code so that it’s readable and easy to extend :slight_smile: .
I do love optimizing code for better performance but in real life it’s rarely needed (but easy to read code is almost always needed :slight_smile:).

1 Like