Home > database >  Javascript: Delete a div that contains (3) in a row <BR>'s in it
Javascript: Delete a div that contains (3) in a row <BR>'s in it

Time:09-15

<div>
        <br>
        <br>
        <br>
</div>

I have an HTML page that has the above div element in it. How can I scan the page an look for a DIV that contains specific items? In this example I know I have three <br> in a row and that's it. The DIV element does not have a class or an ID, and I would like to delete it.

CodePudding user response:

You can target elements in a row by using the sibling selector, . You can make sure the target elements are a direct child of the div by using the > selector.

You can find the div that contains the three br elements like so:

document.querySelector('div > br   br   br').parentNode;

To remove this element from the DOM use the remove method.

const elToDelete = document.querySelector('div > br   br   br')?.parentNode;

elToDelete?.remove();

Edit: Added optional chaining syntax to the answer to show how to prevent undefined errors from being thrown.

CodePudding user response:

You can use the :has pseudo-class to select the div directly

var elem = document.querySelectorAll("div:has(>br br br)");
console.log([...elem])
elem.forEach(x=>x.remove())
<div id=a> a
  <br/>
  <br/>
  <br/>
</div>

<div id=b> b
  <br/>
  <br/>
</div>

<div id=c> c
  <br/>
  <br/>
  <not-br/>
  <br/>
</div>

CodePudding user response:

You can try this:

[].slice.call(document.getElementsByTagName("div")).forEach(function(div){
    var count = 0;
    if(div.children.length === 3)   
        [].slice.call(div.children).forEach(function(br, i){
            if(br.nodeName === "BR")
                count  ;
        });
    if(count > 2)
        div.parentElement.removeChild(div);
});

CodePudding user response:

You can just hide it with CSS

div:has(>br br br) {
  display: none;
}
<div>1</div>
<div><br/><br/><br/></div>
<div>3</div>

  • Related