Home » Javascript » How do you remove tags before and after a special tag in html code using Javascript?

How do you remove tags before and after a special tag in html code using Javascript?

Posted by: admin August 19, 2018 Leave a comment

Questions:

I need to remove all tags in a div with the class of ‘item’ with Javascript with the exception of one tag, the <b> tag.

This is what my HTML document looks like, (My sample code):

    <div class="item">
        <a href="sample-href1">
            <div class="result-image">
                <h5 class="result-cat cat-conf wn">test</h5>
            </div>
        </a>
        <h4>1.
            <a href="sample-href2" title="sample-title2">
                <b> goal tag1 (i need just this tag) </b>
            </a>
        </h4>
        <span class="feature">test</span>
        <div class="compact">
            </br>
            <a href="test12" title="test12"> test12 </a>
            <br>
            <b> some text </b>
            <a href="test123" title="test123"> test123 </a> -
            <a href="test147" title="test147" > test147 </a>
            </br>
            <b>11</b>
            another some text
            </br>
        </div>
        <a href="test159" title="test159" class="download"> test </a>
        <div class="clr"></div>
    </div>
    <div class="item">
        <a href="sample-href1968">
            <div class="result-image">
                <h5 class="result-cat cat-conf wn">test418</h5>
            </div>
        </a>
        <h4>2.
            <a href="sample-href215" title="sample-title215">
                <b> goal tag2 (i need just this tag) </b>
            </a>
        </h4>
        <span class="feature">test23</span>
        <div class="compact">
            </br>
            <a href="test12234" title="test12234"> test12234 </a>
            <br>
            <b> some text </b>
            <a href="test12233" title="test12233"> test12233 </a> -
            <a href="test14657" title="test14657" > test14657 </a>
            </br>
            <b>16</b>
            another some text
            </br>
        </div>
        <a href="test15912" title="test15912" class="download"> test </a>
        <div class="clr"></div>
    </div>
    ... (and so on (<div class=item> ... </div>))

i need just to this tag <b> goad tag(1, 2, ...) (i need just this tag) </b>, i want to remove all tags before and after it in this tag <div class=item> ... </div> with javascript.

note : i have many div (<div class=item> ... </div>) in a source file(test.html) and i want to when i loaded page i just have something like this :

<div class=item>
   <b> goal tag1 (i need just this tag) </b>
</div>
<div class=item>
   <b> goal tag1 (i need just this tag) </b>
</div>
...

I am extremely new to Javascript, Can anyone help me with this problem?

Answers: