Ways to design a JavaScript-generated element

I am attempting to customize a text box generated using JavaScript by assigning an ID to the created element in the following manner:

const x = document.createElement("INPUT");
x.setAttribute("type", "text");
document.getElementById("textBoxForText").appendChild(x);
window.data.appendChild(x);

Here is my CSS:

.textBox {
  border: 2px solid red;
  border-radius: 4px;
}

Despite trying to reference the element by its ID in my HTML file, it doesn't seem to be working:

 <div id="textBoxForText" class = "textBox"></div>

Is there a way to resolve this issue without resorting to innerHTML?

Answer №1

Utilize the class attribute to style elements -

const button =
  document.createElement("button")
  
const text =
  document.createTextNode("Click me")
  
button.setAttribute("class", "custom-button") // <--
button.appendChild(text)
document.body.appendChild(button)
.custom-button {             /* custom class selector, .custom-button */
  padding: 0.5rem;
  color: white;
  background-color: blue;
  border: none;
  border-radius: 3px;
}

Alternatively, you can use the id attribute -

const header =
  document.createElement("h1")
  
const titleText =
  document.createTextNode("Hello World!")
  
header.setAttribute("id", "page-title") // <--
header.appendChild(titleText)
document.body.appendChild(header)
#page-title {           /* id selector, #page-title */
  font-size: 24px;
  color: black;
  text-decoration: underline;
}

Or try using the style attribute for styling -

const buttonText = (s = "") =>
  s.replace
    ( /([A-Z])/g
    , (_, m) => `-${m.toLowerCase()}`
    )

const toCssStyle = (o = {}) =>
  Object
    .entries(o)
    .map(([ k, v ]) =>
      `${buttonText(k)}:${v};`
    )
    .join("")

const customButtonStyles = {      /* javascript object, customButtonStyles */
  padding: "0.5rem",
  color: "white",
  backgroundColor: "blue",
  borderRadius: "3px",
}

const btn =
  document.createElement("button")
  
const btnText =
  document.createTextNode("Styled Button")
  
btn.setAttribute("style", toCssStyle(customButtonStyles)) // <-- 
btn.appendChild(btnText)
document.body.appendChild(btn)

Answer №2

Should the script load before or after the div with the specified ID? Consider using defer or async to affect script loading order

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

Executing Javascript with Ajax requested data - A guide to making your script run smoothly

Battlefield Page In the graphic provided, there is a battlefield page featuring 20 users. To capture and store this data in a MySQL database, I have created a JavaScript script. However, an issue arises when trying to collect data from the next page after ...

Loading a series of images in advance using jQuery

I have a series of frames in an animation, with file names like: frame-1.jpg, frame-2.jpg, and I have a total of 400 images. My goal is to preload all 400 images before the animation begins. Usually, when preloading images, I use the following method: v ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

Having difficulty grasping the concept of integrating Google Sheets API into my project

Being a newbie in web development, I am trying to extract data from a Google sheet and visualize it within a Javascript-animated canvas object. However, navigating through the Google Sheets API documentation has been quite challenging for me. Although my ...

``There seems to be a problem with the radio buttons where the selection disappears when

I'm facing an issue with a radio button group I created. It's functioning properly, but the selection disappears when clicked outside of the radio button. Can someone assist me in resolving this problem? Here is the link to the jsfiddle for refer ...

Is there a way to conceal JSON objects within a three.js scene using the loader.load function?

I am working with multiple JSON files in my three.js project and loading them using loader.load. The files are displayed when I click on the corresponding text content. How can I unload or hide an object with a second click? Below is the code I am curren ...

What is preventing me from iterating through a dictionary or an array of keys?

After trying to log the dictionary using console.log(JSON.stringify(this.idTitleDict)) as suggested by @Kobe, I noticed that it was showing empty curly braces. All the code related to this dictionary (including its declaration and population) can be found ...

Sticky CSS - A guide to making aside elements fill the entire available height

How can I create a grid layout where the aside is sticky to top: 0 and fills all remaining height (e.g. 100% of height), but when scrolling down, the aside height should be changed to 100% minus the footer's height? Is it possible to achieve this with ...

Positioning the image to appear behind the Canvas

As I near the end of the game, I'm encountering an issue where the background image overlaps the Canvas. How can I resolve this problem? -Translated by Google Link to game Link to game with background ...

Tips for adjusting the size of Material UI icons

My Material UI icon size doesn't align naturally with the button: https://i.sstatic.net/l1G98.jpg Button code snippet: <Button variant="outlined" startIcon={<FacebookIcon />}> </Button> Here is the complete example ...

"Exploring the Mini Drawer feature on Material UI brings up a whole new page for the Link

Currently, I am working on a project that involves updating stocks using Material UI. I have implemented a mini drawer from Material UI, but when I click on the menu link, it routes to a new page instead of rendering on the homepage itself. In my App.JS f ...

Obtaining the index of items that are returned by using the limit and sorting by descending CreateAt

My first experience with Parse has been great so far. I've successfully worked on reading and writing data. Now I am faced with a seemingly simple task, but in the Parse context, it feels like a challenge to implement and my usual search skills are n ...

Is there a way to show new chat messages instantly without needing to refresh the entire page?

Creating a real-time chat application presents the challenge of displaying new messages instantly without requiring a page reload. Exploring different methods like reloading only the chat message container or treating new messages as individual chatMessage ...

What is the best way to apply a :visited selector specifically to the most recently visited webpage?

I've noticed that all the pages I've visited on the site have now changed to the color I chose. However, my goal is for only the last page I viewed to be in the color I assigned. Thank you! ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...

Unable to execute JavaScript on Node.js

I recently installed Node.js so I could run some JavaScript codes on LeetCode, but unfortunately, I encountered an issue. I then tried installing the Code Runner extension on VS Code to see if that would help, but this is the output I received: [Running] n ...

I am experiencing an issue in my React application where the component is not being rendered when using a nested route with React Router Dom v6. Despite the

On my main page, I have a sidebar and a content display area that shows the selected option. The issue arises when I click on a link in the sidebar - it doesn't change anything in the content display section, only the URL changes. If I define the rout ...

Establish Angular data for all fields in the form

Being a beginner in Angular, I'm struggling with creating a form to update user information. Here's a snippet of my controller: // Fetch organization data from the database dataService.allOrganization().then(function ...

When a ng-model is added, the input value disappears

i am currently working on a form that contains angular values. <tr ng-repeat="alldata in c.da"> <td>{{alldata.id}}</td> <td><input type="text" class="form-control" value="{{alldata.name}}" ...

Angular UI Bootstrap modal experiencing issues with model binding

Can someone help me with a simple example using Angular UI Bootstrap modal service? I am having trouble with model binding as the expected "Doing something..." message is not displaying on the modal dialog, instead "{{message}}" is shown. What changes do I ...