Issues arise when attempting to include a hyphenated '_' attribute to a tag via the assign method within a function

Currently, I am utilizing a function to dynamically generate input-groups based on the number chosen by the user:

const tag = (tag, className, props = {}) => 
    Object.assign(document.createElement(tag), {className, ...props});

Everything is functioning correctly except when I include a hyphenated field in the call like

tag("div", "collapse", {id: "card" + cardCount, data-parent: "#parentList"}))

Whenever 'data-parent' attribute is used, it triggers an error. I even tried using ['data-parent'] but still encountered the same issue. How can I resolve this and make it work?

Answer №1

Make sure to enclose 'data-parent' in quotes.

tag("div", "collapse", {id: "card" + cardCount, 'data-parent': "#parentList"})

By the way...

To learn more, check out the documentation here

UPDATED

Object.assign() is not suitable in this context as it is primarily used for object modifications, while document.createElement() creates a DOM element that allows you to use the setAttribute method to add attributes.

Therefore, the tag function should be implemented like this:

const tag = (tag, className, props = {}) => {
    const el = document.createElement(tag);
    el.className = className;
    Object.keys(props).forEach(
        key => el.setAttribute(key, props[key])
    );
    return el;
}
...

tag("div", "collapse", {id: "card" + cardCount, 'data-parent': "#parentList"})

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

Iterating through JSON array using Jquery and making POST/GET requests

I can't seem to get my code to loop over the entire JSON array, despite trying multiple tricks and making various changes. Using AJAX to Retrieve Data function FetchData() { $.ajax({ type: "POST", url: "htt ...

Type of result from a function that returns a linked promise

In my class, I have a method that returns a chained promise. The first promise's type is angular.IPromise<Foo>, and the second promise resolves with type angular.IPromise<Bar>. I am perplexed as to why the return type of doSomething is an ...

Utilize Browserify to Dynamically Load all Files within a Directory

As a newcomer to Browserify and JavaScript build systems in general, I find myself in a state of utter confusion. I have successfully set up Gulp for my builds, but recently I have been exploring Browserify to bundle my code, mainly to organize my code in ...

How to retrieve a Typescript variable within an ngIf conditional statement in Angular

How can I access a TypeScript variable inside an ngIf statement? TS: public data: string; HTML: <td> <div *ngIf="data === 'BALL' ; else noplay" >{{ play }}</div> <ng-template #noplay> {{ gotohome ...

Update the input type on the fly

Hey there, I've got a bit of an unusual question. I'm looking to create a form with fields that vary for each user, like a text input or a checkbox. I attempted using Angular to achieve this: <div ng-controller="myCtrl" ng-repeat="x in prova" ...

Unable to build an optional Node.js dependency using the Angular compiler

Within my npm library, there exists a code snippet that appears as follows: let _Buffer: typeof Buffer; let _require: NodeRequire; let _readFile: (path: string, callback: (err: (NodeJS.ErrnoException | null), data: Buffer) => void) => void; try { ...

Tips for styling my date using MomentJS

I am currently using moment.js for displaying dates in my application. The date format is determined based on the locale stored in the variable clientLanguage. I have tried various approaches, including the following: moment(myISODate).locale(clientLang ...

What is the process for closing the lightbox?

My code is supposed to display a lightbox as soon as the page loads, similar to a popup window. However, there seems to be an issue with closing the lightbox when clicking on the 'x' button at the corner of the box. Unfortunately, the current cod ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

What steps can I take to make sure that the asynchronous initialization in the Angular service constructor has finished before proceeding?

Hello experts, can you advise on ensuring that asynchronous initialization in the service constructor is completed before calling other functions within the class? constructor() { var sock = new SockJS(this._chatUrl); this.stompClient = Stomp.ov ...

Adding values to a knockout data table without refreshing the page

I am currently experiencing difficulties with refreshing my knockout.js DataTable. I have a data table that loads correctly on page load using the attached function method. I also have multiple buttons (Display All, Allowed, Not Allowed) that display the t ...

Error: When refreshing the webpage, a TypeError occurs because the property '1' is attempting to be read from an undefined object

Retrieving the user collection from firebase: const [userInfo, setUserInfo] = useState([]) useEffect(() => { if (currentUser) { const unsubscribe = db .collection("users") .doc(uid) .onSna ...

A component designed to capture and respond to events triggered by its child elements

I have recently delved into the world of vuejs and discovered that in order to send data from a child component back to its parent, we can use this.$root.$emit('name-of-event', myobject); The parent component can then receive this data by using ...

Retrieve the most recently updated or added item in a dropdown list using jQuery or AngularJS

Having a multiple select element with the chosen jquery plugin, I am trying to identify the latest selection made using the change event. Struggling to locate a simple method to access the most recent selection, I am currently inspecting the last item in ...

infinite loop issue with beforeRouteEnter

I'm experiencing an issue with Vue Router. The scenario is to load / initially, retrieve data from there, and then navigate to the /chat/:chatId route to display the interface using the :chatId parameter obtained from an API. The routes configured a ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

Creating a persistent overlay carousel in Bootstrap 4.1 - a step-by-step guide

I am trying to create a carousel overlay for Bootstrap 4.1, but for some reason, the .carousel-control-prev-icon and .carousel-control-next-icon are not functioning properly. How can I get the icons to work? I only want one overlay that covers all the slid ...

Having trouble displaying dynamically generated texture from a fragment shader in ThreeJS

I've been working on creating a texture using a Three.WebGLRenderTarget and then trying to access it in a fragment shader in the following stage. The concept is to execute the first stage once to generate a complex and costly SDF map, and then access ...

The alignment of the table header and body becomes misaligned when attempting to freeze the header

I am currently working on making the header visible while scrolling down the page. I managed to achieve this by using display:block; in the CSS for the body element. However, I am facing an issue where the columns of the header are not aligned with the ...

Tips for designing a unique CSS ellipse effect for text styling

Hey there! I have a list of titles in a drop-down menu as strings, for example: "Bharat Untitled offer #564", "Bharat Untitled offer #563" The titles are quite long, so we want to display the first eight characters, followed by '...' and then ...