$('#cont > fieldset').each(
function(index){
var $self = $(this);
// Here how to get child elements? How to write this selector?
//$('$self > div') ?? this seems does not work.
});
$self.find("div"); // return all descendant divs
or:
$self.children("div"); // return immediate child divs
depending on whether you want immediate children or any descendants.
You can even do this to get immediate child divs, but children is prettier :
$self.find(">div");
Look at the .children method in jQuery. This will get direct children of the element, e.g.:
$self.children('div') // returns divs that are direct children
You can also use the similar .find method if you need to go deeper than one level.
$self.find('div') // returns divs that are direct children, or children of children
Also, you can select using $self as the context, like:
$('div', $self) //returns all divs within $self
using children
$(this).children('div')
or
using find
$(this).find('div');
look on this post
You can use the children() method, to get all immediate children of self.
var children = $self.children();
Related
I have an interface that switches between displaying different div elements. When it switches which element it displays, I need to access a specific child node of that div element, with each div element having their children arranged differently.
The childNodes and children property both return an object that can only select children with item(index) which is annoying to use as the relevant child element's index is different in each div. For Protractor, I used the webmanager.by(selector) which was able to search with other parameters than index. Is there something similar I can use to select the child node with data-relevant="true". I am also unsure if that attribute is the best way to specify in the HTML which child node is relevant.
This is an Angular application if that helps.
If you want to select the child node with data-relevant="true" from some parent element, you could use the selector method
element.querySelector()
That would return the first matching element...
in your specific case it could be something like
parent-element.querySelector( "[data-relevant='true']" );
or if you want to select all paragraphs p with the data-relevant attribute value true within the parent div: parentDiv.querySelectorAll( "p[data-relevant='true']" );
You can find some examples on
http://www.w3.org/TR/selectors-api/#processing-selectors
An alternative would be to use a special class to identify which child node is relevant...
you could get this element/or many elements with getElementsByClassName(someClassName)
Code Sample With .querySelectorAll() method:
<script type="text/javascript">
window.addEventListener("load", init, false);
function init(){
var parentDiv = document.getElementById("divWithChildren");
var relevantChildren = parentDiv.querySelectorAll( "[data-relevant='true']" );
alert (relevantChildren[2].id); // this will give the id of the 3rd child element with data-relevant='true'
}
</script>
Let's say I have some sibling DOM elements that exist only within a jQuery selection:
var $container = $('<div></div><span></span>');
I want $div to only contain <div></div>, so I try to remove the <span>:
$container.find('span').remove();
// Note that span still exists:
console.log($div.length === 2);
What's the right way to solve this?
Your current selection is your <div> element. You need to find your span within there and call .remove() on that.
The parameter passed to .remove() does not find elements within the current collection, it filters it.
var $div = $('<div><span></span></div>');
$div.find('span').remove();
This doesn't modify the current selection so this isn't ideal, but I ended up finding a solution using .not():
$div = $div.not('span')
What is the best way to count elements of a particular class within another element?
I have the class of the parent element, but there are other elements with that class. So if for example I have an element that i get to like this:
$(document).on('click', '.countButton', function(){
var parent = $(this).parents('parentDiv');
});
How can I put that element into a selector to count it like this:
$('.parentDiv > .childDivs').length;
Is there someway to convert an element into a selector, or something that points to that element? If that makes sense..
Thanks!
So after var parent = $(this).parents('parentDiv'); you have the element you want and you just want its children with a certain class? If so
parent.children('.childDivs').length;
For direct descendants or:
parent.find('.childDivs').length;
To find elements with the 'childDivs' class at any depth with parent
Yes, you can use the parent element as context for the search:
$('.childDivs', parent).length
Which is the same as:
parent.find('.childDivs').length
Could you perhaps use:
document.querySelectorAll('.parentDiv > .childDivs').length?
I am trying to delete the child element in the dom from its parent using jquery.
Here is the code snippet.
$('#delete').live('click' , function() {
var strchild = m.split("/",2)[1];
var c = group.children(strchild);
c.remove();
});
strchild contains the id of the child element. group is the parent object. I am getting the right child element in the variable c. But the remove function fails.
Can some help me out here.
Thanks.
If you have
strchild
as the id of the element you want to remove, you can do
$("#" + strchild).remove()
assuming it is the only element with that id (it should be, that's the whole point of id).
EDIT:
With multiple ids, you would need to reference the parent specifically. This is very simple, since you say in your question that group is the parent object. This answer assumes it is the object itself, rather than the id, as your code sample implies.
$("#" + strchild, group).remove()
Adding the second argument here constrains the selector to the specifications of that second argument. So this will search the parent (group) for an element with the id strchild, and then remove that element.
When I want to get, for example, the 3rd level parent of the element I must write $('#element').parent().parent().parent() Is there a more optimal method for this?
Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():
$('#element').parents().eq(0); // "Father".
$('#element').parents().eq(2); // "Great-grandfather".
Depends on your needs, if you know what parent your looking for you can use the .parents() selector.
E.G:
http://jsfiddle.net/HenryGarle/Kyp5g/2/
<div id="One">
<div id="Two">
<div id="Three">
<div id="Four">
</div>
</div>
</div>
</div>
var top = $("#Four").parents("#One");
alert($(top).html());
Example using index:
//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);
alert($(topTwo ).html());
You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")
Didn't find any answer using closest()
and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:
You can use the closest() function combined with selectors to get the first element that matches when traversing upwards from the element:
('#element').closest('div') // returns the innermost 'div' in its parents
('#element').closest('.container') // returns innermost element with 'container' class among parents
('#element').closest('#foo') // returns the closest parent with id 'foo'
A faster way is to use javascript directly, eg.
var parent = $(innerdiv.get(0).parentNode.parentNode.parentNode);
This runs significantly faster on my browser than chaining jQuery .parent() calls.
See: http://jsperf.com/jquery-get-3rd-level-parent
It's simple. Just use
$(selector).parents().eq(0);
where 0 is the parent level (0 is parent, 1 is parent's parent etc)
Just add :eq() selector like this:
$("#element").parents(":eq(2)")
You just specify index which parent: 0 for immediate parent, 1 for grand-parent, ...
If you plan on reusing this functionality, the optimal solution is to make a jQuery plugin:
(function($){
$.fn.nthParent = function(n){
var $p = $(this);
while ( n-- >= 0 )
{
$p = $p.parent();
}
return $p;
};
}(jQuery));
Of course, you may want to extend it to allow for an optional selector and other such things.
One note: this uses a 0 based index for parents, so nthParent(0) is the same as calling parent(). If you'd rather have 1 based indexing, use n-- > 0
If you have a common parent div you can use parentsUntil() link
eg: $('#element').parentsUntil('.commonClass')
Advantage is that you need not to remember how many generation are there between this element and the common parent(defined by commonclass).
you can also use :
$(this).ancestors().eq(n)
ex: $(this).ancestors().eq(2) -> the parent of the parent of this.
using eq appears to grab the dynamic DOM whereas using .parent().parent() appears to grab the DOM that was initially loaded (if that is even possible).
I use them both on an element that has classes applied it to on onmouseover. eq shows the classes while .parent().parent() doesnt.
As parents() returns a list, this also works
$('#element').parents()[3];
You could use something like this:
(function($) {
$.fn.parentNth = function(n) {
var el = $(this);
for(var i = 0; i < n; i++)
el = el.parent();
return el;
};
})(jQuery);
alert($("#foo").parentNth(2).attr("id"));
http://jsfiddle.net/Xeon06/AsNUu/