Is there a way to distinguish the HTML Elements from the CSS elements and retrieve them individually?

I am working on achieving a specific task and this JS fiddle represents one part of it.

Check out the JS Fiddle here

alert($("#content")[0].outerHTML);

When executed, this code returns the following DOM structure:

 <div id="content">
     <div id="example1" style="width:100px height:100px background-color:red"></div>
     <div id="example2" style="width:50px height:50px background-color:blue"></div>
     <div id="example3" style="width:25px height:25px background-color:yellow"></div>
 </div>

My goal is to dynamically add div elements with inline CSS. I aim to retrieve both the div elements and their CSS attributes separately as text elements in the end.

Answer №1

To efficiently manage your style attributes, consider removing them and storing them in an id-style mapping for later use. Here's a sample approach:

var styleMap = {};

$("#container").children().each(function() {
    styleMap[this.id] = $(this).attr('style');
    $(this).removeAttr('style');
});

// Verification
alert(
    'HTML:\n\n' + 
    $("#container")[0].outerHTML + 
    '\n\nCSS:\n\n' + 
    JSON.stringify(styleMap, null, 4)
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <div id="sample1" style="width:100px height:100px background-color:red"></div>
    <div id="sample2" style="width:50px height:50px background-color:blue"></div>
    <div id="sample3" style="width:25px height:25px background-color:yellow"></div>
</div>

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

Extremely efficient CSS utility classes for supreme performance

I've noticed the rise of CSS utility classes and I'm curious about their impact on performance. Is there a better approach? Option One - creating HTML elements with multiple utility classes like: <div class="padding flex justifyCenter align ...

Once a WordPress user includes a php file

For the past three days, I've been grappling with this issue... calling on all experts for assistance! I manage four distinct Wordpress membership sites, each with its own branding. My goal is simple - to have a .wav file play the plan's name wh ...

Unable to determine the appropriate signature for calling the date function

<td> {{ fundInfo.startDate | date: "yyyy-MM-dd" }} </td> The issue is located in the primeng-test-b.component.html file under src\app\primeng-test-b directory. ...

When the button is clicked, bind the value to an object using the specified key in

I'm fairly new to Vue and I'm looking to generate buttons based on my data and show their information when clicked. The 'pets' object contains keys for id and info. (My actual data is more extensive and my code is a bit more complex, bu ...

Automatically advance to the next input field and go back when the backspace key is pressed after reaching the maximum length

Creating a credit card input field that switches cursor after reaching maximum number length and focuses on previous field when deleting with backspace. (function ($) { $(".nmipay-input-field").keyup(function () { if (this.value.l ...

Bulma: Tips for creating equally sized buttons?

I am working with Bulma CSS and trying to ensure that all my buttons are the same size. Currently, each button appears to have a different size based on the text content. I have looked into using the "is-fullwidth" option, but it makes the buttons too la ...

How can I create an onclick link within an alert message using JavaScript, even when the alert is not consistently displayed?

I am facing an issue with an alert that is supposed to appear under specific conditions on my website. The alert includes a link that should trigger some code when clicked. However, I keep getting an error message saying "ReferenceError: doTheThing is not ...

What is the best way to display the panel during a postback?

I have a group with two radio buttons labeled purchase and expenses. When the purchase radio button is clicked, the panelpurchase will be displayed, and similarly, the panelexpense will show for the expenses radio button. Check out the image of the output ...

Using Ajax and PHP to Trigger a Forced Download

I am trying to develop a download script that enables the Force Download of JPGs. Below is my PHP script: <?php header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Passing Events in JavaScript Explained

I'm struggling with a click event that involves setting a value. @foreach (var item in Model) { <button class="btn btn-small btn-danger btn-flat" type="button" onclick="SetDelete('@item.Id','@Html.Raw(item.Name)')"><i ...

Div displaying with extra space below

UPDATE check out the new jsfiddle link here that effectively showcases the problem I am encountering an issue with white space appearing below my div. This can be seen in 2 photos, one of which is scrolled down: https://i.sstatic.net/yHlXL.png https:// ...

Identifying button clicks using selenium-wire in Python

Is there a way to use selenium-wire in python to capture a full screenshot of a web page and save it as a png file after clicking the submit button? Despite seeing a popup message saying "taking screenshot!!", the actual screenshot file is not being saved ...

What is the method for applying a prefix to component tags in Vue.js?

Currently, I am tackling a project that was passed down to me and have noticed numerous <p-xxxx> tags scattered throughout the codebase, such as <p-page :has-something="val1" :has-another="val2" />, etc. (For example: CompName --> After a b ...

What's the best way to display the mysqli_error message when making an AJAX call with jQuery?

How can I display the mysqli error message during an ajax call? Here is my PHP code: if(isset($_POST['resumetitle']) || isset($_POST['name']) || isset($_POST['dob']) || isset($_POST['gender']) || isset($_POST[&apos ...

Display a div using jQuery when it reaches halfway the height of another div

I have a code snippet that hides the .wp-filter when reaching the bottom of the .wpgb-layout jQuery(window).bind('scroll', function() { if(jQuery(window).scrollTop() >= jQuery('.wpgb-layout').offset().top + jQuery('.w ...

The error message from the Three.js program states: "Attempting to access property '0' of an undefined value is not possible."

To create a captivating animation with quaternion data, the following code snippet is utilized: var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 ); var renderer = new THREE.WebG ...

Is there a way to retrieve the BrowserRouter history from outside of the BrowserRouter component?

Here is a simplified code snippet (using react-router-v5). I am trying to figure out how to access BrowserRouter's history in the logout_Handler() function, even though I am "outside" BrowserRouter. I came across this answer on How to access history ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...