How to get all children text separated by ; in javascript?

Viewed 2270

I have a following problem:

I would like to get text from all children elements separated by semicolon.

See following example:

<div class="parent">        
  <div class="children 1"> </div>
  <div class="children 2 ">TEXT 2</div>     
  <div class="children 3 ">TEXT 3</div>
  <div class="children 4 ">TEXT 4</div>                                         
</div> 

I know, that I can use document.querySelector('.parent').textContent to get TEXT 2 TEXT 3 TEXT 4

But I would like to get TEXT 2;TEXT 3;TEXT 4 (note that before TEXT 2 is no semicolon because children 1 has no text)

Thanks for any help!

3 Answers

Using .children, you can get a HTMLCollection of the child elements to your .parent div. You can then use Array.from() on the HTMLCollection to convert each child to its text value as well as to form an array from the HTMLCollection. You can then use .filter(Boolean) to keep all values which are truthy (ie: non-empty strings), and then .join(';') to join each element in the array to a string using a semi-colon:

const res = Array.from(document.querySelector('.parent').children, ({textContent}) => textContent.trim()).filter(Boolean).join(';');
console.log(res);
<div class="parent">        
  <div class="children 1"> </div>
  <div class="children 2">TEXT 2</div>     
  <div class="children 3">TEXT 3</div>
  <div class="children 4">TEXT 4</div>                                   
</div> 

// Simple Solution

const divs = [...document.querySelector(".parent").children];

const text = divs
  .map(x => x.textContent)
  .filter(x => (x || "").trim())
  .join("'");
console.log(text);

// Better:

const divs = [...document.querySelector(".parent").children];

 const result = divs.reduce((res, cur, index) => {
  const text = cur.textContent.trim();
  if (text) {
   res += (res == "" ? text : `;${text}`);
  }
  return res;
}, "");
console.log(result);

const divs = [...document.querySelector(".parent").children];

let text = divs
  .map(x => x.textContent)
  .filter(x => (x || "").trim())
  .join("'");
console.log(text);


text = divs.reduce((res, cur, index) => {
  const text = cur.textContent.trim();
  if (text) {
   res += (res == "" ? text : `;${text}`);
  }
  return res;
}, "");
console.log(text);
<div class="parent">        
  <div class="children 1"> </div>
  <div class="children 2 ">TEXT 2</div>     
  <div class="children 3 ">TEXT 3</div>
  <div class="children 4 ">TEXT 4</div>                             
</div>

Try this,

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
       let fullText = []; 
        $('.parent').children('div').each(function () {
         let childText = this.innerHTML;
          if(childText.trim().length)
          {
            fullText.push(childText);
          }
        });
        console.log(fullText.join(";"));
      });
    });
    </script>
  </head>
  <body>
    <div class="parent">        
      <div class="children 1"> </div>
      <div class="children 2 ">TEXT 2</div>     
      <div class="children 3 ">TEXT 3</div>
      <div class="children 4 ">TEXT 4</div>  
    </div> 
    <button>Join the children text</button>
  </body>
</html>

Related