Search code examples
javascripthtmldomdom-manipulation

How to search and replace all tags in HTML file using Vanilla JavaScript?


I am not trying to do anything to the content (at least not yet.) What I am trying to do is search for specific tags and replace them with another one.

I got this HTML that is filled with these tags with the SAME ID (I know this is horrible!)

<div dir="rtl" id="book-container">
some text here #1
</div>

<div dir="rtl" id="book-container">
some text here #2
</div>

<div dir="rtl" id="book-container">
some text here #3
</div>

.
.
.

<div dir="rtl" id="book-container">
some text here #49
</div>

<div dir="rtl" id="book-container">
some text here #50
</div>

I am trying to write a function that would search for every <div dir="rtl" id="book-container"> and delete it without deleting the inner text. And then search for every </div> and delete it as well. Then, wrap the entire thing in a <p> tags.

The result should be something like this:

<p>
some text here #1

some text here #2

some text here #3

.
.
.

some text here #49

some text here #50
</p>

Solution

  • Here is my approach to the problem with a comment explaining each step.

    I took a sample of three elements and enclosed them in a body tag:

    /* Create a paragraph element where the content will be displayed */
    const theParagraph = document.createElement("p");
    /* Choosing the elements */
    const soWrongNodes = document.querySelectorAll("#book-container")
    /* For each element, put its content in the paragraph then remove the 
    element */
    soWrongNodes.forEach(soWrongNode => {
      theParagraph.innerHTML += soWrongNode.innerHTML;
      theParagraph.innerHTML += "<br>";
      soWrongNode.remove();
    })
    /* Append the paragraph element to the body */
    document.body.appendChild(theParagraph);
    <body>
      <div dir="rtl" id="book-container">
        some text here #1
      </div>
      <div dir="rtl" id="book-container">
        some text here #2
      </div>
      <div dir="rtl" id="book-container">
        some text here #3
      </div>
    </body>

    Here is a fiddle.js where you can see the result.