HTML attributes vs DOM properties

Speaking of Jake, his recent article HTML attributes vs DOM properties is a good one for all y’all on that journey to senior developer. I could imagine asking this in an interview. I’d say you should straight up know this is the case and learn over time the more nuanced stuff like which properties reflect into attributes and such.

His first block of code outlines how confusing it can be at first:

<div foo="bar"></div>
<script>
  const div = document.querySelector('div[foo=bar]');

  console.log(div.getAttribute('foo')); // 'bar'
  console.log(div.foo); // undefined

  div.foo = 'hello world';

  console.log(div.getAttribute('foo')); // 'bar'
  console.log(div.foo); // 'hello world'
</script>Code language: HTML, XML (xml)

And this is all exacerbated by languages like JSX where it looks like you’re writing HTML but really you’re setting properties and the framework may or may not turn them into HTML attributes.

It's time to take your JavaScript to the next level

Leave a Reply

Your email address will not be published. Required fields are marked *

Did you know?

Frontend Masters Donates to open source projects. $363,806 contributed to date.