How to select a DIV if its child has any children? - javascript

I'm trying to select any divs on a page if a certain child of theirs has any children of its own.
Here's how the structure looks:
<div id="ID-SOME_LONG_ID">
<div class="GK">
<div id="SOME_LONGID_#1434646398866197"></div>
</div>
</div>
So I want to select all divs with id ID-SOME_LONG_ID only if the GK DIV has any children. It may or may not.
ID- stays the same and SOME_LONG_ID changes with each one.
The other one SOME_LONG_ID is the same on as the parent, and after the # it's a 16 digit number that is random.
Would using Regex be a good idea to look for them or maybe using jQuery's .children() like $( ".GK" ).children()?
Thank you!

Use :has(), :empty, and :not()
$('#ID-SOME_LONG_ID:has(.GK:not(:empty))')
However, note, :empty will fail if you want real children without text nodes. In that case you can do
$('.GK').filter(function() {
return $(this).children().length > 0;
});

Related

Select every element that isn't a parent to any elements

I am developing a game that glitches at some point through using the CSS filter: invert(1); property. However, when you use that property on body, it makes everything position: absolute;. This is not good because I need most elements to be fixed, and everything goes to a negative top and not visible. How can I effectively get all elements in a list that isn't a parent to any other elements, but included if it has text? Any answers or other stack overflow topics would be nice!
Here is some of my code:
// In a working loop called Repeat()
if(Glitch == 1) {
document.querySelector(".ChangableStyles").innerHTML = "* {filter: invert(1)}"
} else {
document.querySelector(".ChangableStyles").innerHTML = ""
}
Edit: Since all of you are asking, the .ChangableStyles tag is a style element. The filter on everything applies when I change the innerHTML of that style tag to valid CSS styles. I don't want to be rude, but I have the .ChangableStyles thing figured out. Thank you.
You mention you already have a list of elements, but it's not clear how you're generating that list. I've gone ahead on the assumption you're wanting to "select" all elements in <body></body> that don't have any children.
You can use a combination of Array.from(), your pre-existing selection logic, and a filter() using node.childElementCount === 0 to accomplish what you describe. However on higher-complexity DOMs this will be computationally expensive, so I would implore you to re-consider your design instead of opting for this route. To be clear, this will meet your requirement of selecting ANY Node in the DOM which has no child elements ("isn't a parent to any other elements"), which includes any script, style or other "user-invisible" nodes in the body.
document.getElementById('get-elements-button').addEventListener('click', function () {
console.log(Array.from(document.body.getElementsByTagName("*")).filter(function (node) {
return node.childElementCount === 0;
}));
});
<div class="has-child-elements">
This is a child element
</div>
<div class="has-no-child-elements">
</div>
<div class="has-child-elements">
This is also a child element
</div>
<button id='get-elements-button'>Get elements with child elements →</button>

JQuery how to find the closest element that is neither a parent nor a child of the current element?

Say I have HTML that looks like this:
<div>
<div>
<div class="calendar start">
</div>
</div>
<div>
<div class="calendar end">
</div>
</div>
</div>
We can assume that the start and end will always be on the same "level" of a branch from each other, and will at some point share a common parent.
Without knowledge of the exact HTML structure, how would I find calendar end from calendar start? What if they are nested further down?
Edit: For clarification. I want to start at start's parent. Search all child elements for end. Then move to the next parent, and search all child elements...etc till I find end. I am wondering if this is possible with built in JQuery functions, without writing my own DOM traversal logic.
You can do it like below, But it is a costlier process.
var parentWhichHasCalEnd =
$($(".calendar.start").parents()
.get().find(itm => $(itm).find(".calendar.end").length));
var calEnd = $(".calendar.end", parentWhichHasCalEnd);
DEMO
Explanation: We are selecting the .start element first, then we are retrieving its parent elements. After that we are converting that jquery object collection to an array of elements by using .get(). So that we could use .find(), an array function over it. Now inside of the callBack of find we are checking for .end over each parent element of .start, if a parent has .end then we would return that parent. Thats all.
You could get more understanding, if you read .get(), .find(), and arrow functions.
You can use jQuery#next() method from .start parent element
var startSelector = $('body > div > div:nth-child(3) > .start')
var endSelector = secondStart.parent().next().find('.end');
I think this method is faster rather than jQuery#children() method, but you can benchmark it if you want to
btw you may check my answer based on this JSBin
i don't know if i got this right but have you tried children function in jquery
$( ".calender" ).children( ".end" )
and for the parent you can use parent() function so you can first check the parent then the children or vicversa
edit:
if you dont know the exact structure the better way is to find the common parent and then search it's children :
$( ".calender.start").closest('.common-parent').children('.calender.end');
closest function give the nearest parent
Try:
$('.start').parent().parent().find('.end');

How to hide all but one child(grandchild) of element in dom

I have a container for all my elements and I hide all of its children like so :
$("#svgContainer").children().hide();
I have two elements that are the 'SVGContainer''s grandchildren :
#canvasParent & #canvasChild.
I have tried doing this :
$("#svgContainer").children().hide();
$("#canvasParent").show();
$("#canvasChild").show();
This doesn't seem to work, probably because the display:none; gets given to the parent not the child.
How do I go about hiding every one of the SVGContainers children except for the elements with id's : #canvasParent & #canvasChild.
Here's a fiddle of the layout I have : http://jsfiddle.net/o9zowx3b/1/
Notice it hides all elements still, I think this is due to them being grandchildren not children of the svgContainer
This should work as requested.
$('#svgContainer').children().not('#canvasParent').not('#canvasChild').hide();
Here is a fiddle, specially for you!
Good luck.
What you're wanting to do is hide all of the siblings of a particular element. That's relatively simple with jQuery using the .siblings method:
$("#svgContainer").children().hide();​​​​
This will hide all elements on the same level, in the same parent element.
You can also do it with single selector:
$("#svgContainer > :not(#canvasParent,#canvasChild)").hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="svgContainer">
<div id="canvasParent">canvasParent</div>
<div>should be hidden</div>
<div id="canvasChild">canvasChild</div>
</div>
This will select all children except the 2 children.
$("#svgContainer").children().not("#canvasParent,#canvasChild").hide();

jQuery select child of closest element

Basically I want to be able to select the div level2 parent from the child level4 div. My application does not has such classes, otherwise I'd just select level2 :)
<div class="level1">
<div class="level2">
<div class="level3">
<div class="level4"></div>
</div>
</div>
<div class="level2"> <!-- this is hidden -->
<div class="level3">
<div id="start" class="level4"></div>
</div>
</div>
</div>
I start with $('#start') and search for the first parent which is visible, but I'm not seeing a way to return the child of that parent. Searching for $('#start') inside the parent seems very wasteful as I start with a sub child to begin with.
$('#start').closest(':visible') // returns level1
$('#start').closest(':visible').first() // returns the first level2. I can't just use second because the number of level2s can change.
$('#start').closest(':visible').children().each(function(){ /* do some search to check it contains `$('#start')` }) // seems very wasteful.
Another way to look at what I'm trying to say would be; start in the middle, find the outside (the visible element), and move one element in.
How about this:-
$('#start').parentsUntil(':visible').last();
This will give you all hidden parent div's until its visible parent and last() wil give the outermost parent which is hidden. last is not a selector on position it is the last() in the collection.
You want the .has() method
Description: Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
$('#start').closest(':visible').children().has('#start');
See fiddle for example.
You say that the classes don't exist...why not add them? It would make thinks much easier to find. The class names don't need to have actual styles associated.
var allLevel4 = $('#start').closest(':visible').find('.level4');
var firstLevel4 = $('#start').closest(':visible').find('.level4')[0];
var secondLevel4 = $('#start').closest(':visible').find('.level4')[1]; //also, #start
Use .filter():
$('#start').closest(':visible').children().filter(':first-child')
.find() is also good for selecting pretty much anything.

jQuery looping through .children of .children

I've been looking over previously asked questions and can't seem to find a solution for my scenario...
I'd like to be able to loop through all children and children of children, etc...
the markup from design looks similar to this
<div>
<div>
<label></label>
</div>
<div>
<label></label>
</div>
<div>
<label></label>
</div>
</div>
I'd like to be able to select all labels within a specific div, regardless of their direct parent.
I'd like to be able to select all labels within a specific div, regardless of their direct parent.
It's just CSS selector notation. Assuming that <div> has an ID of myDiv:
$('#myDiv label').each(function ()
{
// do stuff
});
You do not need to keep stepping down through children in order to find labels within a specific div. This will do the job for you:
$('#idOfDiv label')
$('div label') will select any descendant of that div, regardless of depth. If you want it to be children or children of children, you can select like $('div > label, div > * > label')
Use the find function (instead of children) like so: $('#container').find('label')
$('div:first').find('label') will give you each label element
To select all labels:
$('label').something();
To select all labels contained in a div:
$('label', 'div').something();

Categories