'get InputName of div element using js, no jquery please

I have a variable that consists of an HTML tag as below:

let customDiv = '<div class="MuiAutocomplete-root" name="ApplyTo">Hello</div>';

I want to fetch the "name" which outputs --> "ApplyTo"... from the above customDiv variable. I don't want to use jquery. Wanted to implement it with vanilla javascript. Thanks.



Solution 1:[1]

You can either use string manipulation techniques like Regex:

customDiv.match('name="(.*?)"')[1]

Splitting or substrings:

customDiv.split('name="')[1].split('"')[0]

Or get a full on DOM going by using the <template> element.

let template = document.createElement('template');
template.innerHTML = customDiv;
let name = template.content.firstChild.getAttribute('name');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Schokokuchen Bäcker