Reputation: 21
I want to save my all HTML tags to array like:
Var a = '<p> hi</p> <h2>hello</h2>'
Result like :
result = [
0:"<p> hi</p>"
1:"<h2>hello</h2>"
]
Upvotes: 2
Views: 1452
Reputation: 583
Here is the most simple and easy method I found for this. I hope it will help someone!
var tags = [];
var alltagsObjects = this.document.body.children;
for(i=0; i < alltags.length; i++){
tags.push(alltags[i].outerHTML);
}
console.log(tags);
Upvotes: 0
Reputation: 583
I got the solution but it is not 100% perfect. Check this code, I have extracted the child html elements of the div element with id "demo". You can filter the output array for removing the undefined and split the array element that containing two html elements.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Testing Web</title>
</head>
<body>
<div id="demo">
<h1>I am here</h1>
<p>I am a paragraph</p>
<div class="div">
<h3>I am h3 tag</h3>
</div>
</div>
</body>
<script>
var arr = [];
var x = document.querySelector("#demo").childNodes;
x.forEach(element => {
arr.push(element.outerHTML);
});
console.log(arr);
</script>
</html>
Upvotes: 3
Reputation: 4768
In your example you can use:
/
< // Match literal <
> // Match literal <
.*? // Match any character zero or more times, non greedy
<\/ // Match literal </
> // Match literal >
/g
Your example :
var str = '<p> hi</p> <h2>hello</h2>'
const arr = str.match(/<.*?>.*?<\/.*?>/g); // ["<p> hi</p>","<h2>hello</h2>"]
console.log(arr);
however I do not recommend to parse HTML with regex.
see more: RegEx match open tags except XHTML self-contained tags
Upvotes: 0