skip to Main Content

I need to somehow unwrap these lines of text and append them as plain text to the p element without all the divs, using js. How can i do that?

The result i am after is to go from this:

    <p>
      <div class="line">
        <div>
          some text
        </div>
      </div>
      <div class="line">
        <div>
          some text
        </div>
      </div>
      <div class="line">
        <div>
          some text
        </div>
      </div>
    </p>

to this:

<p>
  some text some text some text
</p>

Below is what i am trying right now, which is not much at the moment.

const lines = [...document.querySelectorAll('.line')]

lines.forEach((el, index) => {
  
})

3

Answers


  1. You can use a loop to build an array from the text content contained within the .line div elements. You can then use that to set the content of the p.

    Note that the following example also calls remove() on the .line div elements, as they are not contained within the p because they are block-level elements, so the HTML as it stands is invalid:

    const lines = [...document.querySelectorAll('.line div')];
    const content = [];
    lines.forEach(line => {
      content.push(line.textContent);
      line.parentElement.remove();
    })
    document.querySelector('p').textContent = content.join(' ');
    <p>
      <div class="line">
        <div>
          some text
        </div>
      </div>
      <div class="line">
        <div>
          some text
        </div>
      </div>
      <div class="line">
        <div>
          some text
        </div>
      </div>
    </p>
    Login or Signup to reply.
  2. Let’s get the parent P so we can operate on it…

    var P=document.getElementsByTagName('p')[0]; 
    

    Now display and observe the differences between these three…

    P.innerText
    
    
    P.textContent
    
    
    P.innerHTML
    

    Which one has joined all the text contained in all the paragraph’s children?

    A little exercise for you. 🙂

    Login or Signup to reply.
  3. If I understood your question right, you want to get the text content of the parent <p> element.

    Add an id attribute to the element:

        <p id="paragraph">
          <div class="line">
            <div>
              some text
            </div>
          </div>
          <div class="line">
            <div>
              some text
            </div>
          </div>
          <div class="line">
            <div>
              some text
            </div>
          </div>
        </p>
    

    Then access its text content wrapped out of element tags like this:

    let text = document.getElementById("paragraph").textContent;
    
    text; // "some text some text some text"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search