Skip to content

jQuery create element with attributes

  • by

To create a new element with attributes using jQuery, you can use the $('<element>') syntax to create the element and then use the .attr() method to set the desired attributes.

$('<element>', {
  attribute1: value1,
  attribute2: value2,
  // additional attributes
});

Example

// Create a new <div> element with attributes
var newDiv = $('<div>').attr({
  id: 'myDiv',
  class: 'myClass',
  'data-custom': 'someValue'
});

// Append the new element to the document
$('body').append(newDiv);

OR

// Create a new <a> element with attributes
var newLink = $('<a>', {
  href: 'https://example.com',
  target: '_blank',
  text: 'Click Me'
});

// Append the new element to the document
$('body').append(newLink);

jQuery creates an element with attributes example

Simple example code that demonstrates creating a new <button> element with attributes using jQuery:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery Create Element with Attributes Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="container">
    <!-- Existing content -->
  </div>

  <script>
    $(document).ready(function() {
      // Create a new <button> element with attributes
      var newButton = $('<button>').attr({
        id: 'myButton',
        class: 'myClass',
        'data-custom': 'someValue'
      }).text('Click Me');

      // Append the new button to the container div
      $('#container').append(newButton);
    });
  </script>
</body>
</html>

Output:

jQuery create element with attributes

When you run this HTML page in a browser, it will create a new button element with the specified attributes and append it to the “container” div.

Another example

Creating a new <a> element with attributes.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery Create Element with Attributes Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="container">
    <!-- Existing content -->
  </div>

  <script>
    $(document).ready(function() {
      // Create a new <a> element with attributes
      var newLink = $('<a>', {
        href: 'https://example.com',
        target: '_blank',
        text: 'Click Me'
      });

      // Append the new link to the container div
      $('#container').append(newLink);
    });
  </script>
</body>
</html>

Do comment if you have any doubts or suggestions on this jquery code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading