Search

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

Frontend Masters logo

Frontend Masters is the best place on the web to really learn JavaScript. We have a complete learning path from the biggest and best teachers in JavaScript to help you make the most out of the web's biggest language.

Leave a Reply

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

Frontend Masters ❤️ Open Source

Did you know? Frontend Masters Donates to open source projects. $313,806 contributed to date.