bullC
bullC

Reputation: 58

jQuery :has selector filter trouble

I have some containers with ids="container1", "container2", "container3"... They can have one of two types of tags inside: tables or canvas. I want to hide one of them depending on the device orientation. I have tried with this

$('[id^=container]:has(canvas)').hide();

or

$('[id^=container]:has(table)').hide();

but both hide all the containers, don't filtering their inside tags.

Upvotes: 0

Views: 188

Answers (4)

bullC
bullC

Reputation: 58

I didn't realized I had a global container with id= "container*". What a silly mistake. Sorry for stealing your time, and thank you everyone!

Upvotes: 0

Thriggle
Thriggle

Reputation: 7059

If you know the element by which you want to grab the container is not nested within additional tags, you can use the parentNode property of an HTML element to climb up the DOM tree and hide the parent.

document.querySelector("[id^=container] > table").parentNode.style.display= "none";

Example that demos the concept:

document.getElementById("input").addEventListener("change", function() {
  document.getElementById("container1").style.display = "block";
  document.getElementById("container2").style.display = "block";
  document.querySelector("[id^=container] > " + this.value).parentNode.style.display = "none";
});
#container1 {
  border: 1px solid red;
}
#container2 {
  border: 1px solid blue;
}
<select id="input">
  <options>
    <option value="table">Hide the table</option>
    <option value="canvas">Hide the canvas</option>
  </options>
</select>
<div id="container1">Table
  <table></table>
</div>
<div id="container2">Canvas
  <canvas></canvas>
</div>

Upvotes: 1

Chin Leung
Chin Leung

Reputation: 14941

You can use classes on your containers instead of ids. Here's a JSFiddle demo.

For better performance in modern browsers, use $( "your-pure-css-selector" ).has( selector/DOMElement ) instead.

Source: https://api.jquery.com/has-selector/

Basically I made a 3 containers. One with a table, one with a canvas and one with nothing.

<div class="container green">
    <table></table>
</div>
<div class="container blue">
    <canvas></canvas>
</div>
<div class="container red"></div>

And a quick CSS to have the divs visible.

div.container{
    display: inline-block;
    height: 50px;
    margin: 10px;
    width: 50px;
}

div.green{
    background-color: green;
}

div.blue{ 
    background-color: blue;
}

div.red{
    background-color: red;
}

And to complete it, a jQuery that executes when the document is ready.

$(document).ready(function(){
   $('div.container').has('canvas').hide(); 
});

Upvotes: 1

void
void

Reputation: 36703

You can do

var x = $('[id^=container]').find("table").length;

// Will be 0 if no table inside it

if(x==0) { .. }
else { .. }

Upvotes: 1

Related Questions