Home  »  CodeProgrammingSnippetsTechnology   »   How to Use jQuery to Add an Attribute to an HTML Element

How to Use jQuery to Add an Attribute to an HTML Element

Posted: August 3, 2022 | by Site Host

This first example shows how to add a single attribute to an HTML element.

$('#elementId').attr('attributeName', 'attributeValue');

This is how setting multiple attributes works. Quotes are optional when defining the attribute name.

$('#elementId').attr({
  id: "TheId", 
  title: "Meaningful details",
  class: "class-name", 
  "data-name": "Alexis" // attributes names which contain dashes(-), should be wrapped in quotes.
});

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.