Home > Software engineering >  Remove empty headings that contain additional empty html tags
Remove empty headings that contain additional empty html tags

Time:10-15

I have a script in my code to remove all empty heading tags so they're not read by screen readers:

    $("h1:empty, h2:empty, h3:empty, h4:empty, h5:empty, h6:empty").replaceWith('');

but it's not picking up heading tags that contain additional empty html like <h2><strong></strong></h2>

How can I also remove these?

CodePudding user response:

You need to use text() property.

$('h1, h2, h3, h4, h5, h6').each(function(){
    if( $(this).text().trim() === '' )
        $(this).remove();
});

CodePudding user response:

Here is how to do this with vanilla JavaScript:

document.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach(el =>
  !el.textContent.replace(/(\s|\n) /g, '') && el.remove());
<h1>abc</h1>
<h2>def</h2>
<h3>
  <strong>
  
  </strong>
</h3>

CodePudding user response:

Try this in JavaScript

const tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
const nodes = document.querySelectorAll(tags.join(','));
nodes.forEach(elm => {
   if (elm.innerText.trim() === "") {
      elm.remove();
   }
});
console.log(document.querySelector("#result").innerHTML);
<div id="result">
<h1>Hello</h1>
<h2><strong>   </strong></h2>
<h3>Element</h3>
<h4> </h4>
<h2>
  <p>
    <strong>   </strong>
  </p>
  <span> </span>
</h2>
</div>

CodePudding user response:

You can use :only-child pseudo class to select elements which are the only child of a parent element, remove the node, then check if the parent node has .children, if not remove the parent node

let nodes = document.querySelector("div")
            .querySelectorAll(":only-child");

nodes.forEach(node => {
  if (!node.childNodes.length) {
    let parent = node.parentNode;
    node.parentNode.removeChild(node);
    if (!parent.children.length) {
      parent.parentNode.removeChild(parent)
    }
  }
});

console.log(document.querySelector("div").innerHTML);
 

I tested it on the following code

<div>
    <div>
        <p></p>
    </div>
    <div>
        <p>Some content</p>
    </div>
</div>

CodePudding user response:

This script would be helpful:

function onlyHaveEmpty(el){
  el = $(el);
  result = true;
  if(el.is(':empty')){
    return true;
  }else{
    if(el.children().length==0){
      return false;
    }else{
      el.children().each(function(idx, child){
        if(!onlyHaveEmpty(child)){
          result = false;
          return;
        }
      });
      return result;
    }
  }
}

$(":header").each(function(idx, el){
  if(onlyHaveEmpty(el)){
    el.remove();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<p>Hello!</p>
<h1></h1>
<h3>It's me.</h3>
<p>World!</p>
<h2><strong></strong></h2>
<h2><strong>Hi!</strong></h2>

  • Related