---
title: "Redefining DOM Object's Behaviour"
description: "Using Object.defineProperty with setAttribute to redefine DOM element properties. Practical notes and code examples on in JS."
url: "https://h3manth.com/scribe/redefining-dom-objects-behaviour/"
canonical_url: "https://h3manth.com/scribe/redefining-dom-objects-behaviour/"
markdown_url: "https://h3manth.com/scribe/blog/redefining-dom-objects-behaviour.md"
publishDate: "2013-09-05T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript","dom"]
word_count: 119
reading_time_minutes: 1
x_markdown_tokens: 339
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Redefining DOM Object's Behaviour

> Using Object.defineProperty with setAttribute to redefine DOM element properties. Practical notes and code examples on in JS.

[Object.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) is useful for defining or modifying properties. But I faced an interesting scenario redefining a video element's `src` attribute.

## The Naive Approach (Causes Recursion)

```javascript
var video = document.createElement('video');
var videos = { comedy: '', drama: '' };

Object.defineProperty(video, 'src', {
  set: function(type) {
    this.src = videos[type];  // Infinite recursion!
  }
});
```

This causes `InternalError: too much recursion` (FF) or `RangeError: Maximum call stack size exceeded` (Chrome).

## The Solution: Use setAttribute

Since video is a DOM node with IDL attributes, we can use `setAttribute`:

```javascript
Object.defineProperty(video, 'src', {
  set: function(url) {
    this.setAttribute('src', videos[index]);
  }
});

video.src = comedy; // Now works as expected!
```

The trick is that `setAttribute` bypasses the property we just defined!
