I have a variable that consists of an HTML tag as below:
let customDiv = '<div 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.
CodePudding user response:
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');