It is impossible for JavaScript to set the position attribute directly in the element's style property

I'm new to javascript and I need some help. I created a function that adds a div with the id "test_div" to the body. However, when I try to set the position using "element.style.position", it doesn't work. I figured out that I can apply styles using "element.style.cssText" instead. I even tried using a variable with "document.getElementById()" after creating the element, but that didn't work either. I'm not sure what I'm doing wrong. Any assistance would be greatly appreciated. Thank you for your help. Please excuse any mistakes in my English.

Here is the HTML file:

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="test.js">
</script>
</head>
<body>
    <button onclick="add('Clicked ', 0)">Click</button>
</body>
</html>

And here is the JavaScript file:

var element_id = "test_div";
var default_timeout = 3;
var element_bg_color = "rgba(0, 0, 0, .5)";
var element_font_color = "#fff";
var element_pointer_events = "none";
var element_position = "fixed";
var element_top = "0";
var element_left = "0";
var element_padding = '.3em .6em';
var element_margin = "0";
var element_border_radius = "0 0 5px 0";

var add = function(string, timeout){
    if(typeof(timeout) === 'undefined'){
        timeout = default_timeout;
    }
    var element = document.createElement('div');
    element.id = element_id;
    element.style.position = "fixed";

    element.style.cssText = "top: 0; left: 0;  background-color: " + element_bg_color + ";  margin: 0;  padding: .3em .6em;   border-radius: 0 0 5px 0; color: " + element_font_color + "; pointer-events: " + element_pointer_events + ";";
    element.innerHTML = string;
    if(document.getElementById(element_id) === null){
        document.body.appendChild(element);
    }else{
        document.body.removeChild(element);
        document.body.appendChild(element);
    }
    if(timeout > 0){
        timeout *= 1000;
        setTimeout(function() {
            document.body.removeChild(element);
        }, timeout);
    }
};

Answer №1

Overwriting all other styles can be done by setting the cssText.

In the example below, setting fontSize to 90px actually results in the span element inheriting font-size and font-weight from the cssText property.

var span = document.querySelector("span");
span.style.fontSize = "90px";

span.style.cssText = "font-size:20px; font-weight:bold;";
<span>Some Text</span>

To avoid this, either set each style property individually or assign cssText first.

Answer №2

Consider the following two lines:

element.style.position = "fixed";
element.style.cssText = "top: 0; left: 0;  background-color: " + element_bg_color + ";  margin: 0;  padding: .3em .6em;   border-radius: 0 0 5px 0; color: " + element_font_color + "; pointer-events: " + element_pointer_events + ";";

We need to switch their order.

To clarify:

element.style.position = "fixed";

The first line sets the position property of element to fixed, resulting in a style attribute like this:

<div id="test_div" style="position: fixed;"></div>

Then, we have:

element.style.cssText = "top: 0; left: 0;  background-color: " + element_bg_color + ";  margin: 0;  padding: .3em .6em;   border-radius: 0 0 5px 0; color: " + element_font_color + "; pointer-events: " + element_pointer_events + ";";

This line essentially overwrites the entire style attribute with the new values specified after the equals sign.
Your element's style will now be modified as follows:

<div id="test_div" style="/* lots of things here, but NOT "position: fixed;" anymore */"></div>

For experimentation purposes, you can check out this fiddle link: http://jsfiddle.net/kxqgr913/

Answer №3

Check out this quick example jsfiddle.net/abc123de/ that demonstrates adding a div, attaching a text node to it, and applying some styling. Hopefully, this sheds light on the process for you. To delve deeper into this topic, consider exploring DOM (Document Object Model)

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

Printing from a Windows computer may sometimes result in a blank page

Looking to incorporate a print button into an HTML page, I'm facing an issue. The majority of the content on the page should not be included in the printed version, so my approach involves hiding everything in print and then showing only the designate ...

The combination of CSS3's 100% height and flexible boxes is resulting in unexpected and erratic

I'm attempting to design a webpage without a scrollbar by utilizing CSS3 box-flex. This is my current code: <html> <body style="height:100%;display:-webkit-box;-webkit-box-orient:vertical;"> <!-- height set to 1000px --> <div sty ...

Positioning elements next to each other in jQuery on mouse over - while also addressing scrolling issues in a div

After tinkering with this interesting concept of mouseover combined with absolute positioning divs on a jsFiddle, I encountered some unexpected results. The code was inspired by a stackoverflow thread on positioning one element relative to another using j ...

In React js, I wanted to display the animation specifically on the "add to bag" button for the added item

When I click the "add to bag" button, all other buttons also display the animation. How can I make sure that only the clicked button shows the animation? Any suggestions? <Table responsive> <thead> <tr> ...

Retrieving Information From a Targeted div Identifier with PHP

Possible Duplicate: read XML tag id from php How can I retrieve data from a specific div ID using PHP? I want to extract data from a div with the ID of <div id="content">, so that all the content within that div can be stored in a variable. Alt ...

Mongoose opts for the __v field over a traditional date field

My current model setup is causing unexpected behavior: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const NewModelSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: "users", }, date: ...

What is the best way to retrieve an object within a class?

Exploring a Class Structure: export class LayerEditor { public layerManager: LayerManager; public commandManager: CommandManager; public tools: EditorTools; constructor() { this.commandManager = new CommandManager(); this.lay ...

The life cycle of the request/response object in Express.js when using callbacks

Feel free to correct me if this question has already been asked. (I've done as much research as I can handle before asking) I'm really trying to wrap my head around the life cycle of request and response objects. Take a look at the following co ...

employing the dimensions of the browser's viewport within a conditional statement

Recently, I came across this JavaScript code that helps in fetching the current viewport size: //get viewport size var viewport = function(){ var viewport = new Object(); viewport.width = 0; viewport.height = 0; // the more standards compliant browsers (m ...

Dynamically update selectable dates in Bootstrap datepicker based on availability

I've integrated WMS data into my website using Leaflet and have implemented a bootstrap datepicker that restricts date selection to a predefined array of dates by utilizing the beforeShowDay method. Now, I'm faced with the challenge of updating ...

The webpage hosted on Heroku displays a blank background, requiring users to refresh the page with an F5 key

I developed a group chat program using Python microframework flask, vanilla JavaScript, and Flask-SocketIO. The program is deployed on heroku and can be accessed here: . After deployment, I encountered the following issue: While the program worked fine o ...

Caution: It is important for every child in a list to have a distinctive "key" prop value. How can a shared key be used for multiple items?

When I click on a header from my list, an image should appear. However, I'm encountering an error that needs to be resolved. I've been struggling to find a solution for adding unique keys to multiple elements in order to eliminate the error. Des ...

Utilize Google Maps' Java Script feature to include a second address on the map

I have successfully implemented the code to display an address on a map instead of latitude, but now I am stuck. I tried adding a second var addresss, but my coding knowledge is limited. Can someone please assist me? <html> <head> <meta n ...

Swap the hyperlink and heading upon clicking

I need to implement a function where a sort bar changes URLs and titles on click. For example, when a link like this is clicked: <a href="http://localhost/11/affiliate/?post_type=affiliate&orderby=title&order=asc ">Title ASC</a> It sh ...

What is the best way to extract text from a string that is enclosed by two particular words?

Using Ajax, I am extracting the complete HTML code from JSON. Once fetched, the string appears as follows : <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" cont ...

Is it possible to change the activation of a link from a double click to just a single click in Angular 5?

I am currently working on an Angular 5 app and have created a navigation component that displays different tabs/links. When a link is active (being viewed), the tab is highlighted with a border to resemble the front of a file folder. However, I am facing ...

The Ubuntu virtual machine hosted on Google Cloud is experiencing difficulties connecting through Node.js using an external IP address

const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.listen(3000, function(){ console.log('Server is now live on port 3000' ...

A guide to organizing page components across multiple `/pages` directories in a Next.js application

As I delve into my first project using Next.js, I find that my pages directory has expanded significantly. Now, I am keen on organizing my pages by grouping them into modules, resulting in a structure like 'src/modules/*/pages/*'. In my quest fo ...

What is the method for displaying a div adjacent to a password input field?

I am attempting to display a password verification box next to an input field. The current logic is functioning properly, but the box containing all password requirements is not appearing in the correct position. Instead of being positioned adjacent to the ...

Unfamiliar function detected in the updated Vue Composition API

I am currently in the process of converting a basic SFC to utilize the new Vue CompositionAPI. The original code functions perfectly: export default { data() { return { miniState: true } }, methods: { setMiniState(state) { if ...