Creating dynamic div elements with a button click in JavaScript / jQuery

Hey, do you know how to dynamically add a div when a button is clicked using JavaScript/jQuery? I want the added div to have the same formatting as the div with the class "listing listing_ad job".

Here is the code I have tried using jQuery:

$('#btnAddtoList').click(function(){
var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
  //newDiv.style.background = "#000";
  document.body.appendChild(newDiv);
});
.listing {
  border-bottom: 1px solid #ddd;
  float: left;
  padding: 0 0 5px;
  position: relative;
  width: 559px;
}

.listing:hover {
  background: #f5f5f5 none repeat scroll 0 0;
  border-bottom: 1px solid #ddd;
  cursor: wait;
}

a:hover {
  color: #ff5050;
}

.subtitle {
  width: 430px;
  font-weight: normal;
  font-size: 12px;
  font-family: Arial;
  color: #7f7f7f;
}

.info {
  float: left;
  margin: 10px 15px 5px;
  min-width: 500px;
  
  clear: both;
  color: #7f7f7f;
  margin: 15px 44px 15px 0;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAddtoList">
Add to list
</button>

<div class="listing listing_ad job">
  <h4>
   <a>
  Excellent Opportunity For Internship at Diamond
  </a>
  </h4>
  <div class="subtitle">
  Lahore, Punjab
  </div>
  <div class="info">
  This is Info / Description.
  </div>
</div>
<!-- ************************ -->

<div class="listing listing_ad job">
  <h4>
  <!-- Src: http://jobs.mitula.pk/internship-program-lahore-jobs -->
  <a>
  Excellent Opportunity For Internship at Diamond
  </a>
  </h4>
  <div class="subtitle">
  Lahore, Punjab
  </div>
  <div class="info">
  This is Info / Description.
  </div>
</div>
Jsfiddle: http://jsfiddle.net/mr4rngbL/3/

Answer №1

Absolutely, you have the ability to do so - simply include jQuery in the script of the document, and ensure to encase the code within document.ready function.

$(function() {
    $('#btnAddtoList').click(function(){
        var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
      //newDiv.style.background = "#000";
       $('body').append(newDiv);
    });
});

Here is an example http://jsfiddle.net/mr4rngbL/5/

Additionally, here is an example demonstrating what you mentioned in the comment: http://jsfiddle.net/mr4rngbL/6/

Lastly, here is another example as per your request in the comment: http://jsfiddle.net/mr4rngbL/7/

Answer №2

Here is a Solution Using Pure JavaScript

function createNewDiv(parentId, text, attributes) {
  var newDiv = document.createElement('div');
  var parentElement = document.getElementById(parentId);

  for (var key in attributes) {
    if (attributes.hasOwnProperty(key)) {
      newDiv.setAttribute(key, attributes[key]);
    }
  }
  newDiv.innerHTML = text;
  if (parentElement) {
    parentElement.appendChild(newDiv);
  }
}

var clickButton = document.getElementsByTagName('button')[0];
if (clickButton) {
  clickButton.addEventListener('click', function() {
    // dynamically change the newly created div
    createNewDiv('container', 'Hello World!', {
      'class': 'some-class',
      'data-example': 'example'
    });
  });
}
<button>Add New Div</button>
<div id="container">

</div>

Answer №3

A simple way to insert a div using jQuery is to do it on a button click. Start by adding a click event listener to the button:

$('button').on('click', insertDiv);

Next, define the function that will insert the div (in this example, the div will be inserted into an element with the class name 'container'):

function insertDiv() {
    $('.container').append('<div>').addClass('entry entry_advertisement job');
}

I hope you find this solution useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate classes into <li> elements within WordPress?

I'm currently in the process of building my WordPress theme from scratch, but I've run into a roadblock when it comes to adding custom classes to the < li > tags alongside those that are automatically generated by WordPress. Below is the co ...

Exploring the beauty of ASCII art on a webpage

Having trouble displaying ASCII art on my website using a JavaScript function, the output is not as expected... This is how it should appear: https://i.sstatic.net/MCwPb.png And here is the code I am trying to implement for this purpose: function log ...

Using PHP and JavaScript to enhance functionality around a hyperlink

I am trying to incorporate a small piece of Javascript on my website to ensure user confirmation. While I have successfully used the 'onclick' function with buttons, I am facing difficulty implementing it on a link. Here is the link in question: ...

Issue with getStaticProps in Next.js component not functioning as expected

I have a component that I imported and used on a page, but I'm encountering the error - TypeError: Cannot read property 'labels' of undefined. The issue seems to be with how I pass the data and options to ChartCard because they are underline ...

Steps to fully eliminate the recent action panel from Django's administrative user interface

Is there a way to completely remove the recent action panel from Django admin UI? I have searched extensively but all the information I find is about clearing the data in the panel from the database. What I'm looking for is a way to entirely eliminate ...

I've encountered the error of receiving a __PHP_Incomplete_Class Object when attempting to create a session using jQuery-ajax

I have defined a new class named FinalResult class FinalResult { var $ReuestAnswer = null; var $givenAnswer = null; var $questionScore = 0; function setScore() { } function getScore() { return $this->question ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

Using Vue JS to apply a filter to data fetched from an API

Within my code, I attempted to retrieve users with the role of Admin and only their usernames from the API JSON data. However, I encountered an issue where it did not work as expected. "response": [ { "profil ...

What is the process for integrating internal PHP code into this HTML form instead of relying on an external PHP file?

I am looking to create a basic HTML form and I want to use the method below for posting. My goal is to include all PHP code within the HTML file itself. (I understand that simply renaming contact.htm to contact.php is an option, but I need guidance on tra ...

Combining nested lists with the tag-it plugin from jQuery, you can create a list inside a list all

Currently, I am utilizing the Tag-it jQuery plugin found at Tag-it, which functions within a ul element. Within my horizontal list (a ul with multiple li elements), I aim to add another li element containing the Tag-it ul list alongside the main horizonta ...

A tool developed in Javascript that allows for the conversion of .ini files to .json files directly on the client

Does anyone know of a JavaScript library that can convert .ini files to .json files on the client-side? I checked out this library, but it doesn't meet my requirements. Here is an example of an .ini file: [Master_Settings:1] Model Name=RC-74DL IP Ad ...

Issue detected: The validation form is encountering errors due to a blank textarea when utilizing jQuery validate and AJAX for

I am currently working on a spring project that involves registering comments on a specific system design. The page layout for this task is as follows: <form id="formularioCadastroComentario" role="form" method="POST" class="form-horizontal"> &l ...

Adjusting picture dimensions with percentages in canvas and jquery

I'm currently working on a one-page project that involves a canvas where users can click to add or place images randomly. I have made progress with most of the functionality, but as a beginner in jquery and canvas, I am struggling to set a maximum siz ...

Challenges of aligning a modal overlay in the middle of mobile screens

Currently, I am developing a website and encountering a specific issue with the modal structure. When viewing it on Codepen using Chrome devtools and toggling the device toolbar to simulate mobile screens, everything appears fine. However, when opening the ...

Attempting to implement scroll-based animation on my webpage

Having trouble integrating this animation (from codepen) into my website. It works fine on its own, but when I try to add it to my site, it doesn't show up. I want it to appear in the middle at the bottom of the background image. Check out the codepe ...

Customizing a ControlsFX PopOver in a JavaFX application

I am looking to personalize the appearance of a JavaFX PopOver control. I have a button that triggers the display of the PopOver. Below is a functional example: package custompopover; import javafx.application.Application; import javafx.event.ActionEvent ...

Guide on retrieving a value from a function that invokes $.getJSON

function searchAndRetrieve(searchTerm) { var defaultResult = 1010; var resultValue = defaultResult; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { ...

Utilize D3's pie chart to showcase the data in JSON's individual collections

I am currently working on creating a pie chart that displays the distribution of collections based on their names. I have come across an issue where d3.layout.pie().value() only evaluates specified array values. Is there a solution available to extract the ...

In JavaScript, provide a boolean response to a callback function from a separate function

Working with the jQuery validate plugin involves utilizing a submitHandler callback function. This function determines whether the form submission should proceed based on its return value - false will prevent submission, while true will allow it to go thro ...

The malfunction of Bootstrap modal in iterative scenarios

I am currently developing a comprehensive method for handling AJAX requests in my JavaScript code, but I am facing some issues with the Bootstrap modal not functioning as intended. Here is the HTML structure: <div class="modal fade" id="consult_modal_ ...