Ways to verify if an element possesses an attribute or not

I am working with an HTML string and my goal is to add an id attribute to all <form> tags that do not already have one.

However, I am encountering an issue when a <form> tag's child already has an id.

<html>
<body>
  <form class="class1">
    <input id="hello" type="text"/>
  </form>

  <form class="bye">
    bye
    <input type="text"/>
  </form>
</body>
</html>

In the first <form>, there is an <input> with an id already, so it does not get a new id added. I only want to target the <form> element itself, but it seems to be checking the entire <form> tag.

This is what I have tried:

const htmlString = `<html>
<body>
  <form class="class1">
    <input id="hello" type="text"/>
  </form>

  <form     class="bye">
    bye
    <input type="text"/>
  </form>
</body>
</html>`

const idPrefix = "MyPrefix";

let modifiedHtmlString = htmlString;

let formIndex = 1;
let startIndex = modifiedHtmlString.indexOf("<form");


while (startIndex !== -1) {
  const endIndex = modifiedHtmlString.indexOf("</form>", startIndex);
  const formTag = modifiedHtmlString.slice(startIndex, endIndex);

  if (!formTag.includes("id=")) {
    const modifiedFormTag = formTag.replace("<form", `<form id="${idPrefix}${formIndex}"`);
    modifiedHtmlString = modifiedHtmlString.replace(formTag, modifiedFormTag);
    formIndex++;
  }

  startIndex = modifiedHtmlString.indexOf("<form", endIndex);
}

console.log(modifiedHtmlString);

Answer №1

If you are working with a string of HTML elements instead of actual DOM elements, you can utilize the following code snippet:

const htmlContent = `<html>
<body>
  <form class="class1">
    <input id="hello" type="text"/>
  </form>
  
  <form id="form2" class="class1">
    <input id="hi" type="text"/>
  </form>

  <form     class="bye">
    bye
    <input type="text"/>
  </form>
</body>
</html>`

const tempDiv = document.createElement('div')
tempDiv.innerHTML = htmlContent
Array.from(tempDiv.querySelectorAll('form')).forEach((form, index) => {
  if (!form.hasAttribute("id")) {
    form.setAttribute("id", `form_${index+1}`)
  }
})
document.querySelector('body').appendChild(tempDiv)

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

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

What is the process for extracting Html sub elements from parent elements?

While using my HTML editor, specifically the Kendo Editor, to generate bullets and indent them for sub-bullets, I noticed that the HTML output wasn't as expected. <ul> <li>Focusing on lifetime income replacement <ul>< ...

What methods can I use to test a Django view that includes a form?

As I embark on developing an application using Django, I find myself faced with a particular challenge. I have created a view that receives a form from the HTML code and then searches the database for any instances of a model based on the values specified ...

Utilize the parent element's background color as the color for the box-shadow styling

Currently working on enhancing a radio button design by incorporating an inset box-shadow. If you're interested, check out this CodePen showcasing my progress so far. The main challenge I'm facing is getting the background of the .radio-button ...

Concern regarding the lack of timely response

I am experiencing an issue with the responsiveness of my template. When I test it online on various websites, everything appears to be working perfectly. However, when I try to view it on my HTC one, the responsiveness is terrible and not fully functional. ...

Verify if the items in the array are based on ASCII codes

I'm looking to extract ASCII codes from elements within an array. Here's a sample array: var elem = ["Joe", "M"+String.fromCharCode(13)+"ry", "Element_03", "Element_04"]; I tried using a for loop to scan through the array and check for ASCII co ...

Check if there is a registered user in the database using React

How can I use useEffect to list users from the database and then create a condition that checks if the user entered in a textfield exists or not? Even though I store API values in the user state, when I enter a valid user in the textfield, it always shows ...

Exploring the process of parsing JSON data within a Spring controller that has been transmitted via a post

I have managed to find a solution for posting JSON data using Angular 2 and reading it in the Spring controller. However, I believe there might be a simpler way to achieve this. Here is the class definition: export class EmovieCat{ id:String = "test ...

Leveraging ajax data to enhance visual representation in graphs

Having trouble fetching data from a database to display it in a graph.js graph. I've attempted setting a timeout for the async callback from Ajax, but nothing seems to be working. Any suggestions on how to make this work would be greatly appreciated! ...

Struggling to implement validation in the Ajax form, still encountering issues with getting it to

Having previously posted here without success, the answers provided did not solve my issue. I am encountering a problem with AJAX in a form where error or success messages are not displaying. If anyone can identify what I might have missed, I would great ...

What is the best way to showcase the items stored in local storage in a list format?

As a newcomer to React, I find myself struggling with a specific issue related to displaying data on a checkout page. I am trying to show a summary of items that the user has purchased from their cart, which are stored in localStorage. Although I can see t ...

What is the best way to retrieve the 'items' data stored in this list?

I am working with a list of data that includes 6 categories - bags, shoes, girls, boys. Each category contains the same type of data like id, items (with properties: desc, id, imageUrl, name, price), routeName, and title. My goal is to loop through all ca ...

What is the method for generating a custom tag (similar to a class) within an option contained in a SELECT element?

I need to create a select box with two options: cars or boats. Here is my initial idea: <select> <option value="1" class="cars">Car1</option> <option value="2" class="boats">Boat1</option> <option value="3" class="ca ...

React app running on local network is unable to make API request [CRA]

I'm currently using Create React App (CRA) to set up my React app. My concern is how to make a locally hosted React app perform API calls. To better explain, I'll have to describe the issue. Right now, my machine's IP address is 192.168.1. ...

Enhancing the performance of sortable array and object structures in Javascript

When working with objects in javascript and needing to maintain a specific sort order, key/value pairs cannot be used. Instead, utilizing an array with features like ES6 map is more suitable. An example structure that could be used is shown below. The id ...

Semi-transparent HTML5 Canvas illustrations

Can I generate partially transparent elements dynamically in canvas? I am currently adjusting the opacity of the entire canvas element through CSS, but I need certain elements to be more translucent than others. My research has not turned up any evidence ...

Utilizing Ajax to update the login form without reloading the page and displaying any errors

I have created a login form that utilizes ajax to handle login errors such as "incorrect password" from my login.php file. Instead of reloading a new page with the error message, it now displays the errors on the same login form, which is working perfectly ...

Fetching images from a WikiJS API endpoint

I need help creating a GraphQL query string to retrieve page data from Wiki JS. Specifically, I am looking for a way to fetch the URL of the first image on the page. Unfortunately, I have been unable to find any information on how to do this in the documen ...

Transmitting HTML markup code

Let's discuss an example with a form that may not be secure or correct: <BODY> <FORM ACTION="" METHOD="post" NAME="test" ID="test"> <INPUT TYPE="text" NAME="testt" VALUE="1"> <INPUT TYPE="reset" VALUE="testtt" onClick="test.s ...

Do we truly need to demolish components that are dynamic in nature?

const validReportComponents = { default: DefaultTemplateComponent } @ViewChild('container', { read: ViewContainerRef }) containerRef: ViewContainerRef; private _componentReference: ComponentRef<any>; constructor( public activeModal: Ngb ...