Javascript how to split plain text html elements into an array?

无人久伴 提交于 2021-02-10 23:21:17

问题


If I have a string containing html elements, what would be an efficient way of creating an array of the sibling html elements?

Trying to use indexOf with the first letter of the opening tag " <" and the last one of the closing tag becomes complicated since there can be child elements.

Simple example:

<p>Hello there</p>

<h1>Thank you</h1>

Thanks in advance!


回答1:


Using regex with js split method we can extract.

Check my code

let a = `<p>Hello there</p><p>How r you?</p>

<h1>Thank you</h1>`
let b = a.split(/<[a-zA-Z0-9]*>([^<.*>;]*)<\/[a-zA-Z0-9]*>/gmi).filter(x=>x.trim() !== '')
console.log(b) //['Hello there', 'How r you?', 'Thank you']



回答2:


I believe this is what you're trying to do.

  <div id="container">
    <div>child 1</div> 
    <div>child 2</div> 
    <div>child 3</div> 
  </div>
  <script type="text/javascript">
      let elements = [], container = document.getElementById("container");
      for(let i = 0; i < container.children.length; i++){
          elements.push(container.children[i].outerHTML);
      }
      console.log(elements);
</script>



回答3:


You can use regex to solve this.

Find all the opening and closing tag using regex and replace with "/" (something else) then split it and then filter the ("") using filter(Boolean)

Code:

var elements = [],container = document.getElementById("container");
  for(let i = 0; i < container.children.length; i++)    {                     elements.push(container.children[i].outerHTML.replace(/<\/?[^>]+(>|$)/g, ""));
   }
   
      console.log("plainTextArray = ",elements);




let bodyHtml = document.getElementsByTagName('div')["0"].innerHTML;

let plainTextArray = bodyHtml.replace(/<\/?[^>]+(>|$)/g, "//").split("//").filter(Boolean)

console.log('plainTextArray = ',plainTextArray);
<body>
<div id="container"><p>Hello there</p><h1>Thank you</h1></div>
</body>



回答4:


You can use like this to get all the texts from the child elements.

let nodeList = document.getElementById('stack').querySelectorAll('*');
let list = [];
nodeList.forEach(function(val){
	list.push(val.outerHTML)
})
console.log(list); 
<div id="stack">
 <p>Hello there</p>
 <h1>Thank you</h1>
</div>


来源:https://stackoverflow.com/questions/54340266/javascript-how-to-split-plain-text-html-elements-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!