JavaScript in a copied style

When using JavaScript to copy a table cell, I encountered an issue where the style was not being copied along with the content. Attempting to directly assign the style from one cell to another did not work as expected.

To ensure that the text-align property was being copied correctly, I had to explicitly set it like this: newCell.style.textAlign = oldCell.style.textAlign;

While this method worked for individual styles, it became cumbersome to remember to add each new style manually. This led me to wonder if there was a way to loop over all the style properties and copy them.

In Chrome, I was able to achieve this by dynamically accessing the style attributes of a cell and applying them to a new cell:

 var strAttribute = GetDomNameFromAttributeName(oRow.cells[1].style[0]);
    var styletocopy = eval('oRow.cells[1].style.'+strAttribute);
    eval("newCell.style."+strAttribute+"='"+styletocopy+"'"); 

Unfortunately, this approach did not work in Internet Explorer. My compatibility testing in Firefox is pending.

Does anyone know of a way to effectively loop through the style elements in Internet Explorer? Alternatively, is there a more efficient method to copy all style properties at once?

Answer №1

eval('oRow.cells[1].style.'+strAttribute)

Avoid using eval in this manner(*). In JavaScript, you can access a property stored in a string by using square brackets. For example, object.plop is equivalent to object['plop']:

to.style[name]= from.style[name];

(*: It's best to avoid using eval altogether whenever possible. Only use it in extremely specific and rare situations.)

Is there a way to iterate over the style elements

The style object should support the DOM Level 2 CSS CSSStyleDeclaration interface. You can loop through the rules and apply them to another element like so:

for (var i=from.style.length; i-->0;) {
    var name=from.style[i];
    to.style.setProperty(name,
        from.style.getPropertyValue(name),
        priority=from.style.getPropertyPriority(name)
    );
}

Can this work in IE?

No, IE does not fully support the CSSStyleDeclaration interface mentioned above, so the previous method won't function in IE. However, there is a simpler approach that will work on both IE and other browsers as well:

to.style.cssText= from.style.cssText;

It's that easy! While IE may not preserve the CSS text perfectly, the difference is negligible for basic inline style replication.

Nonetheless, as Pikrass suggested (+1), if you're copying an entire element rather than just styles, using cloneNode is the most efficient method.

Answer №2

To duplicate a DOM Element along with its content (such as attributes), you can utilize the .cloneNode(true) method:

const duplicatedDiv = document.getElementById('target').cloneNode(true);

Upon execution, the variable duplicatedDiv will hold an identical replica of the targeted div element. The boolean parameter "true" indicates that the content within the element should also be copied.

Answer №3

If you need to transfer all the styling attributes from one node to another, you can achieve this by using the following code:

newElement.setAttribute('style', originalElement.getAttribute('style'))

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

Passing an array of integer arrays to a controller method in ASP MVC using Ajax

I am encountering an issue with my AJAX call when trying to post data entered by the user on the webpage to a controller method. Unfortunately, the data never reaches the controller and always results in an error. I suspect that the problem lies in the typ ...

Guide to incorporating a jade file into a node.js application after executing an Ajax request

While working on my node.js application, I encountered an issue with loading a new HTML file using Ajax on a button click. Despite everything else working perfectly, the new HTML file was not being loaded. This is how I am making the ajax call in my main. ...

Exploring the world of React-Bootstrap elements and properties

I'm currently diving into a Bootstrap home project and it's my first time working with Bootstrap. I came across a tag that has an 'inverse' attribute among others like 'fixedTop', 'fluid', and 'collapseOnSelect& ...

The comparison between dynamically adding elements through Javascript and hiding them using CSS

I am contemplating the advantages and disadvantages of adding elements to a page and setting display:none versus creating a function that dynamically generates the elements and appends them where needed. In my current situation, I am implementing a reply ...

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

toggle back and forth between two div elements

I am trying to create a toggle effect between two divs, where clicking on one will change its border and header color to red while the other div disappears. I have tried using an IF statement in my JavaScript code, but it is not working as expected. Can so ...

Is React failing to identify parameters?

working on my react project, I have an App component which is responsible for rendering multiple child components. Here's how it looks: App render() { return ( //JSX inside <BrowserRouter> <div> <Heade ...

Stacking pictures with CSS and absolute placement

I have designed a webpage where I need to layer three images in a specific order to create a background for content placement without any movement during scrolling. Fixed positioning is not suitable for this purpose. Below is the sequence in which the imag ...

Instructions for changing the background color of a value

I'm working with a code that populates values in table columns, but the text displays in black color. I would like to highlight the text with a blue background. Here is the HTML code snippet: <body> <div class="container"> ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

Issue with Displaying Full-Page Div

My HTML page consists of just one div. The body code is as follows: <div> </div> Here is the corresponding CSS: body { margin:0; height:100vh; width:100vh; } div { height:100vh; width:100vh; color:#000000; } I c ...

Unlocking the hidden treasures: Integrating nested values into Material Table fields via column linking

I am currently working on creating a table with nested data that looks like this: [{ id: 24, name: "DANIEL TSUTOMU OBARA", number: "134", phone: "11111111111", rg: "4034092666", EmployeeStatus: { crea ...

Tips on how to showcase a picture with the focus on the center by enlarging it within

We have a long frame on the page, with an aspect ratio of about 3.5:1 width to height. However, most of the photos being displayed are in a 4:3 ratio, which is larger and not a proper fit for the frame. The customer really wants the long frame and has no ...

Meteor Infinity: the astronomy .save functionality seems to be malfunctioning

Encountering an issue where I am receiving a "post.save is not a function" error when trying to use the .save() function with astronomy v2. The error occurs when attempting to call the .save() function to insert a new document into the database using a Met ...

Container will keep items from spreading out

Experiencing an issue with the card layout in my weather dashboard app. The cards within a container are not spreading out evenly to match the 100% width of the header. I want the container with the 5 cards to be the same width as the header and wrap prope ...

What is the process for retrieving the text element from a React component when using React.cloneElement?

Can I centralize a translation function for all table header elements? const CustomersTable = () => { var headers=<> <th>Name</th> <th>Age</th> <th>Another text</th> </> ...

Eliminate an item from an array of objects utilizing a specific key

Here is the JSON data provided: var data= { 'A' : { 'Total' : 123, 'Cricket' : 76, 'Football' : 12, 'Hockey' : 1, 'None' : 10 }, 'B&ap ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

What is causing the angular ng-repeat table to not sort correctly?

Currently, I am facing an issue with a table that is being populated by Angular: I have provided the code here so you can see the problem in action: http://plnkr.co/edit/qzY4r2XWq1UUJVrcqBsw?p=preview When I click on the a elements, the sort order change ...