Abror_StubBorn
Abror_StubBorn

Reputation: 21

How to save html tags as array?

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

Answers (3)

Back2Lobby
Back2Lobby

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);
  • First we have tags array to store our output
  • this.document.body.children gives us all the children of body tag as an nodelist (a bit like an array) of HTMLElementObjects
  • It also has a property named 'length' where it provides the number of its children. We used it for our loop.
  • Each of these objects have a property named 'outerHTML' (It is same as the innerHTML property but the difference only that it also includes the tags of that element)
  • Now just push all these to our output array.
  • DONE!

Upvotes: 0

Back2Lobby
Back2Lobby

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>

array output

Upvotes: 3

Hamid Shoja
Hamid Shoja

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

Related Questions