Creating an element with a specified class name in javascript: A step-by-step guide

What is the process for creating an element with a specific class name using JavaScript?

I attempted to create an element like the following:

<div class ="dialog_red_top_page">
    <div class ="inner_dialog_red_top_page">
        <p class="dialog_red_top_page_text">
            test
        </p>
    </div>
</div>

However, my JavaScript code did not work. How can I accomplish this task successfully?

http://jsfiddle.net/n5phf/186/

<script type="text/javascript">
$(window).load(function(){        
    $('#myBtn').click(function(){
        var div = $('<div class ='dialog_red_top_page'><div class ='inner_dialog_red_top_page'><p class='dialog_red_top_page_text'>test</p></div></div>');
        div.html("test");
        div.appendTo('#wrapper');

    });
});
</script>

Answer №1

One issue to note is the use of double quotes instead of single quotes around the class attribute.

Another thing to keep in mind is that when using div.html("test");, it will change the HTML of the div to <div>test</div>

To wrap content, you can utilize the .html() method.

$('#myBtn').click(function(){
    var div = $('<div class ="dialog_red_top_page"><div class ="inner_dialog_red_top_page"><p class="dialog_red_top_page_text"">test</p></div></div>');    
    $('#wrapper').html(div);
    // Consider trying out .append instead of .html()
    //$('#wrapper').append(div);
    //$(div).appendTo('#wrapper');

});

Check out the Working Demo

Answer №2

All of your quotations consist of single quotes

Follow this format instead

let element = $('<div class="dialog_red_top_page">'
  + '<div class="inner_dialog_red_top_page">'
  + '<p class="dialog_red_top_page_text">example</p>'
  + '</div></div>'
);  

Answer №3

Enclose the class names with " quotes instead of ' single quotes and do not include div.html("test");. This command is used to replace the HTML content of a selected element with test, essentially removing .inner_dialog_red_top_page and replacing it with test.

View demo on Jsfiddle

Answer №4

To properly escape all single quotes, use a backslash before each one:

var div = $('<div class=\'dialog_red_top_page\'><div class=\'inner_dialog_red_top_page\'><p class=\'dialog_red_top_page_text\'>test</p></div></div>');       

Your code seems to create a div with nested div and paragraph elements, but then you proceed to call:

div.html("test");

This line of code replaces the content inside the .dialog_red_top_page div.

Check out this jsfiddle for demonstration

Answer №5

Here is the correct way to write your code:


$('#myBtn').click(function(){
        $("<div class ='dialog_red_top_page'><div class ='inner_dialog_red_top_page'><p class='dialog_red_top_page_text'>test</p> </div></div>").appendTo('#wrapper');
    });

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

Stopping the iteration through each AJAX call loop after processing the data

I can't seem to keep track of my SO accounts! The issue at hand: My tool allows users to click on each year for the past decade to display a set of data. Some years may not have any data, but users can still browse through them and possibly receive ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

What are some strategies for resolving a parse error in a JSON file?

var personalInfo = { "name": "Belphy Baby", "role": "student", "contacts": { "mobile": "9567166100", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3654535a465e4f070076515b575f5a1855595b"&g ...

Issue with loop detected in <fieldset> tags - prematurely adding closing tag

In the development of my web app using Google Apps Script, I am faced with the challenge of creating a set of checkbox fields for each learner/student, displayed in rows of three. These checkboxes are generated from data stored in a spreadsheet. My goal i ...

Retrieving the Image of an Amazon Product using ASIN

My goal is to locate the image URLs for Amazon products using only their ASIN. For instance: This link pertains to a product with the ASIN B07NVVQL66 in the United States. Clicking on it will display an image of the product http://images.amazon.com/imag ...

Response from successful AJAX call to retrieve data

Here's the code snippet I'm currently working with: var array = []; $('#next1').on('click', function(){ var dataString='company= '+$(this).closest('.inside').find('select').val(); $.ajax( ...

Guide on converting a JSON containing nested JSONs into an HTML table

Currently, I am working with a JSON data structure that contains nested dictionaries. My goal is to create an HTML table where each top-level key serves as a column in the table. The inner key-value pairs should be represented as a single text within cells ...

Creating custom components to encapsulate material-ui functionality

Struggling with the Table component from material-ui? I've divided the table logic into a header and body component, with each row being represented by a different component within the body. export const PRODUCTS = [ {category: 'Sporting Goods ...

Before sending an XHR request with Ajax, access can be granted

My goal is to implement a redirect for ajax requests. In the event of a session expiration, my backend currently redirects to the login page instead of sending data. However, I have come across discussions on StackOverflow highlighting that ajax does not h ...

Babel not compiling code correctly

I'm trying to utilize babel to convert client-side ES6 scripts to ES5 and save it to a file. But my current configuration is simply returning the input code. Here's an example of the code: const babel = require('babel-core'); babel. ...

The Highchart feature endOnTick does not properly align with the maximum value set for the x-axis

We're implementing line charts with Highchart's API and have a requirement to end the xAxis scale with the last value provided in the data and display its tick label. Data: [[2014-08-28, .434], [2014-10-17, .234], [2014-11-5, .134], [2015-01-12, ...

The term 'undefined' does not qualify as a function when analyzing the operation 'c.replace(bo,"-$1")'

Having some trouble with using jQuery effects to show or hide a div. Every time I try one of the following methods, an error pops up in the console. The animation runs successfully for the first time, but then the error appears in Safari console and I&apo ...

Issue with Jquery addclass not activating upon clicking on li element

My menu structure is as follows: <ul class="menu_bg" id="menu-main-menu"> <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-653" id="menu-item-653"><a href="http://apptivowp.apptivo.com/" title="Home">Home&l ...

Learn how to retrieve information using the dash operator in ReactJS

I find it a bit amusing, but I'm encountering an issue. Can anyone lend me a hand with this? So, I'm using an API to fetch some data and it appears that the response from the API is in this format: start-time:2323232 end-time:2332323 Now, when I ...

Retrieving the value from a textbox within a datatable using jquery

Within a data table, I included a textbox column as the second column by appending: var textbox= '<input type="text" class="txtBox">'; However, now I am attempting to retrieve the value of the textbox. Here is what I have tried: var ro ...

When the text exceeds the designated block, it will be fragmented

I have always struggled with text elements not breaking when they exceed the boundaries of their parent element. I understand that setting a max-width of 100px will solve the issue, but it's not an ideal solution for me. I want the text to break only ...

The database threw an error: "Duplicate key found in collection causing MongoError: E11000"

I'm currently in the process of updating an object within an array found in a document "state": [], "users": [{ "ready": false, "_id": { "$oid": "5fb810c63af8b3 ...

What steps can I take to prevent duplicate random numbers from occurring in my selection?

For my application, I incorporate a datepicker from jQueryUI that requires unique IDs for each input element. To achieve this, I implement the following function: var x = 100; $("a").on("click", function(){ console.log(Math.floor(Math.random() * x)); ...

Positioning MDL cards in HTML documents

Seeking guidance on positioning MDL cards alongside existing text. I've attempted various methods without success so far, and the desired outcome has not been achieved. The goal is to have text aligned to the left (which is currently satisfactory) wi ...

What is the best way to style an element while working on a CSSStyleDeclaration prototype?

Instead of using element.style.removeProperty(property) to remove properties one at a time, I have created a utility function that can remove multiple properties at once. By extending CSSStyleDeclaration.prototype. Snippet: declare global { interface CS ...