Custom JavaScript attributes work differently in IE compared to Firefox

Adding custom attributes to HTML tags is a really valuable programming method. It's something I do quite often.

Consider the following code:

<script>
    function DoSomething(el){
        alert(el.contentId);
    }
</script>

<div contentId="123" editable="true" onclick="DoSomething(this)">Some Text</div>

The above code would work in IE6+ but would fail in Firefox.

The solution

In Firefox you need to use one of the following alternatives to read the attribute value back (these also work in IE)

 el.attributes["contentId"];

 el.getAttribute("contentId");

I guess we should all be using these rather than the helpful IE code... old habits die hard though.

Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

Philippe Leybaert said:

When you are using XHTML (as everyone should), you're not allowed to specify your own attributes on html tags. W3C XHTML validation will fail if you do.

The only way to add custom attributes (properties in fact) is by using JavaScript, like this:

document.getElementById("elementID").contentId = "123";

01/Aug/2007 12:19 PM

nvodka said:

"When you are using XHTML (as everyone should)..."

I should obey the speed limit too, but I don't.

Anyway, thanks for this. This is what I was looking for. Helps out the MS/Visual Studio developers.

16/Jun/2009 05:50 AM

NNM said:

This will only work in IE.

Replace .contentId with .getAttribute("contentId")

and it'll work outside of IE.

15/Feb/2010 12:42 PM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.