Manipulate the DOM and remove empty paragraph before and after a figure element?

Asked

Viewed 27 times

-1

Using some Javascript method, how could you remove elements that are soiling HTML?

I have the following HTML:

<div class="container-text">
<p> Teste onon onon noonnoon </p>
<p> Teste onon onon noonnoon </p>
<p> </p>
<figure><img src="/path/img/teste.jpg"></figure>
<p> </p>
<p> Teste onon onon noonnoon </p>
</div>

How could I remove the empty paragraph that is before after <figure> (siblings / brothers)?

I tried so:

function removeParagraphAfterAndBeforeFigure(result) {
        var el = document.createElement('div');
        el.innerHTML = result;
        el.querySelectorAll('figure')
           .forEach(function(figure){
            figure.parentNode.querySelectorAll('p').forEach(function(p){
                 if(p.textContent == '' || p.textContent == ' ') {
                     p.parentNode.removeChild(p);
                 }
            });
        })
        result = el.innerHTML;
        return result;
    }
  • If your tag looks like this <p></p>, without the space inside, type a tag pasted right into the other, you can use the pseudo class :empty CSS to give a None display in that paragraph

  • Do you have to be the direct brother of the figure? If you have one p empty at first, should it stay? Or have to clear any empty paragraph inside the div, no matter where he is?

1 answer

0


It worked that way:

    function removeParagraphAfterAndBeforeFigure(result) {
        var el = document.createElement('div');
        el.innerHTML = result;
        el.querySelectorAll('figure').forEach(function(value) {
            if(value.nextElementSibling.nodeName == 'P' && (value.nextElementSibling.textContent == '' || value.nextElementSibling.textContent == ' ')) {
                value.parentNode.removeChild(value.nextElementSibling)
            }
            if(value.previousElementSibling.nodeName == 'P' && (value.previousElementSibling.textContent == '' || value.previousElementSibling.textContent == ' ')) {
                value.parentNode.removeChild(value.previousElementSibling)
            }
        })
        result = el.innerHTML;
        return result; 
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.