2

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>"
]
2
  • Just make an array and loop through all the elements in the page and push in the array Commented Feb 8, 2020 at 7:31
  • check this stackoverflow question on serializing html Commented Feb 8, 2020 at 8:00

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.