Christian Heilmann

Q&A: Dynamically assigning CSS Floating in JavaScript

Monday, April 2nd, 2007 at 5:09 pm

Q: I am creating some HTML elements using JavaScript and the DOM. All is fine, but I need to define one element as floated to the right. I tried var d=document.createElement(‘div’); d.setAttribute(‘float’,’left’); which seems to do it, but the element is not floated. I tried then to use the style collection with d.style.float = ‘left’; but that didn’t work either. How do you float an element in JS?

A: Your first approach was wrong, as this would add an attribute called “float� to the element and not set the CSS property. The second approach is almost right, but “float� is a reserved word in JavaScript (because of floating point numbers). The correct property of the style collection is called cssFloat (you will also run into the same issue when you try to create labels with a “for� attribute, this one is called htmlFor). This’ll work nicely in Firefox, but Internet Explorer does not support cssFloat (one of the annoying bugs that were still not fixed).

In any case, generating a lot of HTML and defining the style inside your JavaScript is not a very maintainable way of development. It is much easier to keep the annoying little browser CSS support glitches to fix in CSS rather than having to check through a script to find where you changed it. In order to allow for that all you need to do is assign either an ID or a class to the parent element of all your DIVs or add a CSS class to the DIV when you create it. Then you can define the floating in CSS and you don’t need to worry about it any longer. Be aware that you need to use the className property (d.className = ‘foo’) to assign a CSS class to an element and not setAttribute(‘class’,’foo’) as class is another reserved word.

Share on Mastodon (needs instance)

Share on Twitter

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

Dev Digest 146: 🥱 React fatigue 📊 Query anything with SQL 🧠 AI News

Why it may not be needed to learn React, why Deepfake masks will be a big problem and your spirit animal in body fat! 

Dev Digest 147: Free Copilot! Panel: AI and devs! RTO is bad! Pi plays!

Free Copilot! Experts discuss what AI means for devs. Don't trust containers. Mandated RTO means brain drain. And Pi plays Pokemon!

Dev Digest 148: Behind the scenes of Dev Digest & end of the year reports.

In 50 editions of Dev Digest we gave you 2081 resources. Join us in looking back and learn about all the trends this year.

Dev Digest 149: Wordpress break, VW tracking leak, ChatGPT vs Google.

Slowly starting 2025 we look at ChatGPT vs Google, Copilot vs. Cursor and the state of AI crawlers to replace web search…

Dev Digest 150: Shifting manually to AI.

Manual coding is becoming less of a skill. How can we ensure the quality of generated code? Also, unpacking an APK can get you an AI model.

My other work: