Decide which characteristics to serialize

When converting a div into a string using

new XMLSerializer().serializeToString()
, I want to be able to select specific DOM attributes for serialization.

For instance:

let element1 = document.getElementById('element1');
element1.style.color = "blue";
console.log(new XMLSerializer().serializeToString(element1));
#element1 { font-size: 16px; }
<div id="element1">Hello</div>

Instead of ...

<div xmlns="http://www.w3.org/1999/xhtml" id="element1" style="color: blue;">Hello</div>

...I would like to serialize all attributes except the color style attribute:

<div xmlns="http://www.w3.org/1999/xhtml" id="element1">Hello</div>

Is there a way to specify which attributes to include in the serialization when using

new XMLSerializer().serializeToString()
?

Answer №1

  1. Make a deep copy of the tree using node.cloneNode(true) and insert it into a DocumentFragment
  2. Utilize
    fragment.querySelectorAll("[style]")
    to locate all elements with the specified attribute for removal
  3. Delete the attributes from the matched elements
  4. Serialize the fragment

var blah = document.getElementById('blah');
var blah1 = document.getElementById('blah1');

blah1.style.top = "100px";

var frag = new DocumentFragment()
frag.appendChild(blah.cloneNode(true))

for(var e of frag.querySelectorAll("[style]")) {
   e.removeAttribute("style")
}

console.log(new XMLSerializer().serializeToString(frag))

Successfully tested on Firefox version 33

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

Optimal strategy for Retrofitting all JavaScript files to substitute <myArrayObj>.forEach(iteratorFn) with _.each(<myArrayObj>, iteratorFn)

Looking for the best approach to update all JavaScript files by replacing instances of <myArrayObj>.forEach(iteratorFn) with _.each(<myArrayObj>, iteratorFn) I have a number of older JavaScript files that need updating to ensure compatibility ...

Using the jQuery plugin multiple times within one website

I have a decent understanding of jQuery and I'm in the process of developing a plugin. Specifically, it's a dropdown element that I'm working on. Everything functions correctly when there's only one dropdown on the site. However, when ...

I'm receiving the error message "Fatal error: Call to a member function query() on a non-object," what could be causing this issue?

Need help with fixing an error on my private server realmeye. The error message I'm receiving is: Fatal error: Call to a member function query() on a non-object in /home/noxus/public_html/realmeye/index.php on line 112 =========================== ...

Focusing on specific parents to target the same children using CSS and jQuery selectors

Is there a more efficient way to target specific children of select parents in CSS without excessive repetition and lengthening the selector? For instance, if I want to style the first-child paragraph within certain divs. The current CSS method: .funny ...

What is the best way to preserve the state of a component in Angular?

I need to find a way to preserve the state of a data table within my Angular 7 & Typescript application. It's essentially like saving the state of a browser tab. When I navigate to another component and return to the one with the data table, how ...

Having difficulty transforming shapefiles into geojson

I am in need of JavaScript code that can seamlessly convert shapefile files to geojson and vice versa, but I am struggling to find reliable tools to accomplish this task. After some research, I stumbled upon Calvin Metcalf's repository, which claims ...

Issues with the last-child selector in CSS being unresponsive

I am having trouble applying styles to the final <p> in a specific div. I would like to achieve this without introducing a new class or ID. Despite attempting to use the last-child selector, I have not been successful in accomplishing my goal. I ha ...

Interactive pop-up window featuring conversational chat boxes

Trying to create a comment box within a Modal dialog box that is half of the width. The comments in this box should be read-only and created using div tags. Attempted reducing the width and using col-xs-6, but ending up with columns spanning the entire w ...

Hot Loader does not accept this React component for hot reloading

Utilizing https://github.com/stylesuxx/generator-react-webpack-redux for the generator and employing hot-loader, my code functions smoothly when loaded in the browser. However, upon opening the development panel in the browser, I am faced with: React Hot ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

How come my post isn't being saved to the page after I refresh it?

Utilizing Javascript, NodeJS, MongoDB, Express Within my application, a user is expected to enter text in an input field and upon clicking the submit button, the text should appear on the page. I have succeeded in posting text to the page; however, after ...

Transfer the values selected from checkboxes into an HTML input field

I am attempting to capture the values of checkboxes and then insert them into an input field once they have been checked. Using JavaScript, I have managed to show these values in a <span> tag successfully. However, when trying to do the same within a ...

Steer clear of using the onRowClick event if an outputLink is clicked within a RichFaces datatable

What is the best way to prevent the call to onRowClick on a column with an output link in a datatable that targets a new window? <rich:dataTable id="dt" value="#{bean.cars} var="_car"> <a:support event="onRowCli ...

Ways to retrieve keys from the json object below

Working on integrating handsontable with a php backend, I'm attempting to dynamically generate table column headers. This involves creating an array of column names that will be used in handsontable like so: colHeaders: ['ID', 'First&a ...

What is the best way to manage the maximum number of concurrent AJAX requests?

I am currently working on an autocomplete search bar feature. <input type="text" class="form-control" id="text" > <script> $("input").keyup(function(){ let key = $("input").val(); ...

Splitting a CSS hierarchical list into horizontally aligned levels of hierarchy

I am trying to horizontally lay out an ordered list with multiple top level nodes while preserving the vertical layout of child nodes. For example, consider a basic list structure like this: <ol> <li>Top 1 <li>Sub 1</li ...

Modification of text within a text field via a context menu Chrome Extension

Currently, I am embarking on my first endeavor to create a Chrome extension. My goal is to develop a feature where users can select text within a text field on a website using their mouse and have the ability to modify it by clicking on a context menu. Be ...

The issue of double submission persists, with the prevention of the default action

I'm in need of assistance. Within my form, I have two buttons displayed on the page: "Save" and "Publish". Below is the corresponding HTML code: <button type="submit" class="button">Save</button> <button type="button" class="button" n ...

Determining the best times to utilize Grid items for alignment and justification versus when to avoid using them

I am wondering about the appropriate use of Grid item in order to utilize the props of the Grid container such as justify or alignItems. I initially thought that these attributes could only be applied to the Grid item within the Grid container, but my exam ...

What is the best way to adjust my column position in order to make the links clickable?

Looking for help with a mobile version website menu bar design. The issue is that the central "+" button is covering the two icons on either side, making them unclickable. Is there a solution to rearrange this layout? Here is the current design: https:// ...