Extract attributes from a string of HTML containing name-value pairs

Here is a sample string that I need to work with

'<img id="1" data-name="test" src="img_01.jpg" />'

My goal is to extract the attribute name and value pairs from the string, create the element, and apply these attributes.

I have come up with code so far, however, I'm struggling with extracting attribute names and values:

createNode = function(a, b) {
  let name = null;
  let el = null;

  if(/<[a-z][\s\S]*>/i.test(a)) {
    name = a.match(/(\w+)/i)[1];
    el = document.createElement(name);
    // get attributes and apply them
    return el;
  } 
}

createNode('<img id="1" data-name="test" src="img_01.jpg" />');

Answer №1

To convert the HTML string into an element, you could utilize the DOMParser and then simply return that element:

const createNode = (htmlStr) => {
  const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
  const element = doc.body.children[0];
  return element;
};

const img = createNode('<img id="1" data-name="test" src="image_01.jpg" />');
console.log(img.id);

If opting for a regex approach, one method might be:

createNode = function(a, b) {
  const [, tagName, attribStr] = a.match(/^<(\S+)(.*)>$/);
  const element = document.createElement(tagName);
  let match;
  const re = / *([^=]+)="([^"]*)"/g;
  while (match = re.exec(attribStr)) {
    const [, attribName, attribVal] = match;
    element.setAttribute(attribName, attribVal);
  }
  return element;
}

const img = createNode('<img id="1" data-name="test" src="image_01.jpg" />');
console.log(img.outerHTML);

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

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

Steps for creating new users using a post request

I've been working on developing a chat application using react-chat-engine, and everything is running smoothly except for one issue - I'm struggling to figure out how to send a post request to create new users. Below is the code snippet I'v ...

What is the best way to iterate through a JSON object using the stages array provided?

I am facing an issue with parsing the provided json to display the desired output on the screen. These are the steps I need to follow for parsing this json: 1. Extract the stages array from the json - for example, stages ["check_dependency_progress", "sh ...

Bootstrap causing issues with correct display of div element

I'm having trouble getting my divs to display on the same row. It seems like when I have 2 rows, the button is positioned correctly. However, with only one row, the button ends up on the second row. Here is the current layout: https://i.sstatic.net/L ...

Does the syntax for the $.ajax() function appear to be incorrect in this instance?

I am attempting to use .ajax to retrieve the source HTML of a specific URL (in this case, www.wikipedia.org) and insert it into the body of a document. However, the code provided below is not producing the expected outcome. <!DOCTYPE html> < ...

React component encountering unexpected prop value

In my project, I have a Modal component and a Form component. The Modal is a functional component, while the Form is a class component responsible for handling form submissions. The Modal component passes all of its props to the Form component. Within Mod ...

Is there a way to apply filters to jquery datatables during initialization process?

Is there a way to server-side filter datatable during initialization? I attempted the following code: function tableFilter(arg1, param2, value3) { var searchTable = $("#tblsearch").dataTable({ "bRetrieve": true, "b ...

Creating a smooth entrance effect in VueJS using CSS transitions is a breeze

Even though it seems simple, I am struggling to get it to work properly. My goal is to have the existing elements in my list shift to make room for a new element added, and then have the new element appear with a smooth fade transition. I have tried to im ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

Extract words with specified tags from HTML using Python and return them as a list

Is there a simple way to parse HTML, extract the text, and generate a list of tags associated with each word or snippet of text? For instance, in the given HTML code: <em>Blah blah blah</em> blah again <i>and then again</i> The de ...

Looking to replace a background image using javascript?

(apologies for any language mistakes) I have multiple divs with a common background image. I assigned them the same class and set the background image using CSS in style.css which worked perfectly fine. Now, I want to change the background image dynamical ...

Tips and tricks for personalizing the leaflet Lopup component using vue js

Seeking guidance on customizing the design of the LPopup component in leafletjs. I found a helpful guide at: After inspecting the Lpopup in the dev tools, I tried adding CSS styles to the 'leaflet-popup-content-wrapper' selector (please refer to ...

Tool that closely mirrors the functionalities of Google Maps

Seeking to develop an interactive image feature on my website akin to Google Maps but with custom images. Desiring functionalities like drag, scroll, and zoom in/out for enhanced user experience. Interested in any suggested tools or plugins for this purp ...

Maintain HOVER State in CSS Drop Down Menu upon Clicking

I have implemented a CSS Drop Down Menu on my website. In a specific section of the site, I am using the menu links to trigger AJAX-jQuery calls that dynamically change the content of a DIV without the need for page reloading. <script type="text/javasc ...

What steps can be taken to successfully import a JavaScript module without encountering a ReferenceError?

Recently, I created a Javascript export file with the following content: export const A = 1; export const B = 2; export const C = 3; As an experiment, I attempted to import this file into another Javascript document like so: import 'path/export_file. ...

Creating components in reactjs using the render function

Just a quick query – I've been diving into react js recently. Typically, when we create a component in React, we include the HTML template within the render function. I've noticed that most examples consist of small components with minimal HTM ...

What is the best way to declare a minimum and maximum date in HTML as the current date?

I have a question regarding setting the min/max date for a date input in my Angular 6 project. How can I ensure that only dates up to the current date are enabled? So far, I have attempted to initialize a new Date object in the ngOnInit function and set t ...

Encountered an error while trying to retrieve data using the combination of axios, nodejs

Having trouble with my fetch request taking too long and then failing I've tested it on Chrome, Edge, and Postman without success All other fetch requests from the Pixabay API are working perfectly fine I compared my code to previous projects I&apo ...

Retrieve all default and user-defined fields associated with contacts in the CRM 2011 system

In CRM 2011, the contact entities come with a variety of default fields, and I have also included some custom fields. My goal is to retrieve all field names in a JavaScript list. When creating an email template in CRM, you can select fields from a dialog. ...

The (.svg) image does not cover the full width of the page

After creating an SVG image, I encountered a problem when trying to display it on a webpage. Even with the width value set to 100%, the image did not stretch all the way to the edges of the page, leaving small gaps at the edges. I attempted to switch the ...