Explain Codes LogoExplain Codes Logo

How to add/update an attribute to an HTML element using JavaScript?

javascript
attribute-manipulation
cross-browser
jquery
Anton ShumikhinbyAnton Shumikhin·Aug 13, 2024
TLDR

Kick off your attribute manipulation journey by employing element.setAttribute('attr', 'value'):

document.querySelector('.button').setAttribute('disabled', true);

This sprinkles the magic disabled dust on the elements with class .button, Enabling or Disenabling (Yes! I said it) them on your page.

Cross-browser compatibility and direct property access

Browsers are a bit like people; they react differently to stuff. We're talking about those stubborn old folks here (Internet Explorer is glaring at us). Regularly using element.className = 'newbie'; or element.id = 'NewKidOnBlock'; is a silent nod of acknowledgment towards these venerable seniors.

setAttribute() is the peacemaker here. It works beautifully across different environments and maintains order in the chaos world of varying attribute behaviors for specific attributes. However, for the complete browser behavior breakdown of the attribute, visit here.

Handling styles and classes

Changing styles or classes directly is even more sailor-smooth than buttering your toasts:

let divElement = document.querySelector('.divvy'); divElement.className = 'diva'; // From just another div to a diva! Yes with one line! divElement.style.height = '500px'; // Just gave our div some high heels!

Direct property access like the above is like having your cake and eating it too. Efficient and the right way.

Using jQuery for attributes

If you're a jQuery fan or just lazy (we all are sometimes, don't worry), attr() method is your golden ticket to the wonky factory of simplifying attribute shenanigans across multiple elements and browsers:

$('.button').attr('title', 'Do not press!'); // No, seriously don't. Bad things happen!

It just threatened all the .button elements with a "do not press!" tooltip. Rude!

Advanced attribute manipulation

Safefence against Structure "Dom"inoes

Dom structure changes and innerHTML is a notorious headache duo. To avoid unwanted restructuring and annihilating event handlers, it's safer to stick to document.createElement() along with element.appendChild() or element.insertBefore().

Like a Boss: Property style

Attributes are fancy, aren’t they? You can directly access and modify some attributes like they are the boss

let inputElement = document.querySelector('input[type=text]'); inputElement.value = 'Boss entered the chat!'; // Join the boss in the chat

Remember: Not all attributes maintain the charm of beat-sync with properties all the time.

On Tag-ing spree with "tag names"

Nothing like some good old e.tagName action when you need different battle plans for different HTML elements. It shows you the way, or at least the tag.

Attribute manipulation, the safe way

Consistency is Key

Clarity, readability, maintenance. No, not an SAT word list. These are something your code will gain when the method across your codebase is consistent. Does not matter if you use setAttribute or direct property access.

The Curious Case of Browser Quirks

Prime examples of weird old Internet Explorer behaviors are e.getAttribute('class') or e.setAttribute('for', ...)". Be mindful of such quirks and put on your browser support detective hat for your chosen methods.

Knowledge: The Ultimate Weapon

Dive into detailed jQuery's documentation when dealing with jQuery. The more you know, the sharper your tools!