wee hee
wee hee

Reputation: 85

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

<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.

Upvotes: 3

Views: 134

Answers (5)

huwiler
huwiler

Reputation: 954

Best solution that will work cross-browser is to tackle this programmatically. Note that :has() pseudo class doesn't work on Firefox, IE or Opera (see https://caniuse.com/css-has).

Here's a concise functional Javascript approach:

[].filter.call(document.querySelectorAll('div'), el => el.querySelectorAll('br').length === 3)

Upvotes: 1

epascarello
epascarello

Reputation: 207527

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>

Upvotes: 1

g0rb
g0rb

Reputation: 2389

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.

Upvotes: 4

apple apple
apple apple

Reputation: 10604

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>

Upvotes: 3

Bryan C.
Bryan C.

Reputation: 117

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);
});

Upvotes: 1

Related Questions