JavaScript can sometimes present peculiar challenges when it comes to setting style attributes, especially when a DOCTYPE is

It seems like I am encountering an issue when trying to dynamically create and modify a <div> element using JavaScript. The problem arises when I use the XHTML 1 Transitional doctype.

This is how I am generating the <div>:

var newDiv = document.createElement("div");
document.body.appendChild(newDiv);
newDiv.innerHTML = '<div id="myID" style="z-index:9998;border: 1px solid #000000;
border-radius:3px;position:absolute;display:block;top:-10000;left:-10000;width:400;height:400;"></div>';

Initially, the myDiv is positioned outside of the visible screen area.

Later on, when a click event occurs, I execute the following code:

var myDivElement = document.getElementById("myID");
myDivElement.style.top = 200;
myDivElement.style.left = 200;

Everything works smoothly without any issues until I include the doctype declaration in the HTML. Once the doctype is added, the styling modifications fail to take effect.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

With the presence of the doctype, the assignment of values to properties like top, left, width, and height through JavaScript gets ignored. However, specifying units (such as px) alongside these values resolves the problem.

myDivElement.style.top = "200px";
myDivElement.style.left = "200px";

Therefore, it raises the question of how the doctype impacts the execution of JavaScript functions related to styles and potentially other operations as well.

Answer №1

Using numerical values without units is technically incorrect, even if the browser allows it to work without a doctype (browsers behave unexpectedly without a doctype).

The style properties are similar to CSS properties, requiring strings with appropriate units attached. For example, "200px" is valid while 200 alone is not. The properties like left, should be specified using lengths such as "200px" or "10em", percentages, or keywords like auto and inherit. You can refer to the CSS 2.1 spec for more details.

When creating the myID div, remember to include units in your string:

div.innerHTML = '<div id="myID" style="z-index:9998; ' +
    'border: 1px solid #000000; ' +
    'border-radius:3px;' +
    'position: absolute;' +
    'display: block;' +
    'top:-10000px;' +     // here
    'left:-10000px;' +    // here
    'width:400px;' +      // here
    'height:400px;"' +    // and here
    '></div>';

Answer №2

By incorporating the DOCTYPE declaration, you are informing the browser of the specific standard being utilized (such as XHTML 1.0 in your situation). This prompts the browser to adhere to a precise rendering mode, rather than defaulting to a more lenient quirks mode in the absence of a DOCTYPE.

Consequently, this results in stricter interpretation of your code – all dimensions should be accompanied by units (e.g., 200px, 1.2em, etc.). Without a unit, numerical values lack significance and will be disregarded by the browser when not operating in quirks mode.

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

Highlighting table rows using jQuery on click and restoring them on change by toggling between alternating

Hey there, I'm a newbie to jQuery and this is my first post. Spent some time searching but couldn't find exactly what I needed. I'm trying to have alternating row colors in a table; one class as NULL/empty and the other as alt. My jQuery sc ...

Two-way data bindings trigger the digest() function to iterate 10 times

I'm facing issues with angular binding and my experience level in this area is limited. I will be posting all related questions here. I have a piece of angularjs code that is triggering 10 digest() cycle reached errors. After researching similar posts ...

Connect-busboy causing NodeJS issue: TypeError - the method 'on' cannot be called on an undefined object

Recently I encountered an issue with a piece of my code: router.route("/post") .get(function(req, res) { // ... }) .post(authReq, function(req, res) { // ... // Get uploaded file var fstream; req.pipe(re ...

Utilize React to showcase all stored items in localStorage in a Material UI List

I have a storage system with multiple items stored in it. I am looking to retrieve all of them and showcase them using a <ListItem> from Material UI. This is my current code snippet: function saveItem(key, value) { localStorage.setItem(key, value) ...

Creating a PHP JSON response that incorporates an HTML layout is a dynamic

I'm having some trouble with a certain issue: I am attempting to develop a jQuery/AJAX/PHP live search bar. Although I am successfully calling search.php, the response displayed in the console always includes the contents of my master.php file (which ...

Implementing a delay using setTimeOut function to execute an action upon user input

Take a look at this code snippet: $("#test").on("keyup", (e) => { if(e.target.value.length === 3) { setTimeout(() => { console.log("fired") }, 2000) } }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

When should ng-repeat be utilized: only when the object type is an array?

I have a detailed object structure below: $scope.document = { "GENERAL_FIELDS": { "Source_Type": "custom", "Annotations": [ "216/content/Factiva_CM_001/Proteins", "216/content/Factiva_CM_001/Fact" ], "Content": [ " ...

Tips for concealing tick labels in d3 using TypeScript

When trying to hide tick labels by passing an empty string to the .tickFormat("") method, I encountered an issue with Typescript. The error message received was as follows: TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axi ...

How can I store a value or text to track view counts or a counter efficiently?

Recently, I've been trying to implement a view counter on my website, similar to what you see on YouTube. Currently, the number of views stands at 23. I managed to find some code that allows me to increment the view count every time I click on an imag ...

"Triggering an AJAX POST request with a click event, unexpectedly receiving a GET response for

Hello there! I am currently attempting to send an AJAX POST request when a button is clicked. Below is the form and button that I am referring to: <form class="form-horizontal" > <fieldset> <!-- Form Name --> <legend> ...

Scraping a JavaScript page using Python without requiring a browser installation

Currently, I am facing a challenge in scraping an HTML element from a webpage. The content within this element is dynamically generated by Javascript, making it impossible to retrieve using a simple requests.GET: response = requests.get(url). While explor ...

Display a collection of Mongoose objects in a React component

In my development stack, I rely on node js + React. The data I work with comes from mongoose and typically follows this format: { "_id": "61b711721ad6657fd07ed8ae", "url": "/esports/match/natus-vincere-vs-team-liquid- ...

Executing several Ajax requests at once can decrease the speed of the process

When I make simultaneous API calls using Ajax, the process seems to be slow as JavaScript waits for all API responses instead of fetching them asynchronously. For instance, /api/test1 usually responds in 5 seconds and /api/test2 also responds in 5 seconds ...

Using the html5-canvas element to drag connected lines

Here is an example of creating four points and connecting them: sample. My goal is to make it possible to drag the entire line connection when clicking on it, but when clicking on a circle, only that specific circle should be extended (already implemented ...

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

Leverage the Google Maps JavaScript API v3 to retrieve details for multiple locations using the getDetails(request, callback

I successfully integrated the Google Maps JavaScript API v3 to create a personalized store locator for our company's website. While the current code is functional for two stores, it lacks scalability due to the unconventional methods used. My impleme ...

Managing Recursive Promises: A Guide

function Authenticate() { this.invalidAccessToken = false; } Authenticate.prototype.checkTokenValidity = function (accessToken, refreshToken) { var token; var self = this; return new Promise(function (resolve, reject) { Authenticat ...

On mobile devices, the alignment of text in Bootstrap doesn't appear as intended

I'm creating a portfolio website for showcasing my design projects from university. The text in the "my work" section is centered, but it seems misaligned with other elements like buttons when the window width is reduced. What could be the issue? Cod ...

Can you explain the owlItem feature found in owl carousel?

Does anyone have an idea about this? .data("owlItem") How can I find this in jQuery or the console log? I don't think this is a data attribute. .data("owlItem") .data("owlItem") $("#slider_thumb").on("click", ".owl-item", function(e){ ...

Is it possible to run a Universal Windows Platform desktop app on an Android mobile device?

After successfully developing a Universal Windows Platform app in Visual Studio using WinJS, JavaScript, CSS and HTML, I am now interested in leveraging the same code base to create an Android application. Could you guide me on the necessary steps to run ...