How to find first parent element in jquery - javascript

Conside below html -
<div class="container1">
<div class="container2">
<div class="container3">
<div class="container4">
<div class="element">
...
</div>
</div>
</div>
</div>
if I want to get <div class="element"> element and I have reference to the container1. In jquery what I do is,
$(".container1").find(".element")
instead of -
$(".container1").children().children().children().find(".element")
This is process to find any child element when I have reference to any of the parent element. But instead when I have reference to a child element and want to get parent element then every time I have to go one level up -
$(".element").parent().parent().parent().parent()
and I can't do like this -
$(".element").findParent()
I have not come across any method like findParent() in jquery. Is there which I am not aware of? Or is it not there for some reason?

$(".element").parents();
will give all parents of .element(including html and body)
DEMO
To find any specific parent, suppose container1 then
$('.element').parents('.container1')
DEMO
jQuery .parents() generally find all parents, but if you passed a selector then it will search for that.

just use
$(".element").closest('#container1');
if no ancestor with that id is found then
$(".element").closest('#container1').length will be 0

To get the first parent personally I use the following construction:
var count_parents = $(".element").parents().length;
$(".element").parents().eq(count_parents - 1);
Hope, it will be helpful for someone.

Related

How to get nested DOM

How to get nested DOM.
I want to get the nested DOM by Jquery.
For example.
<div id="red">
<div id="member">A</div>
</div>
<div id="blue">
<div id="member">B</div>
</div>
<div id="yellow">
<div id="member">C</div>
</div>
Is it possible to get the each memver id like, yellow.member
I want to do like this.
$("#yellow.member").removeClass("myclass");
The way you wanted to access the child element of #yellow was real close to be correct.
$("#yellow .member").removeClass("myclass");
Notice the added space. The space means to look for another matching element in the descendant tree of the element matched by the previous selector.
Now it's your markup that is wrong. You just cannot use the same id more than once. The concept of id comes from long before the computer age... An "identification" is unique per definition!
Here is how your markup should look like... in a working example where the interval is just for fun:
$(document).ready(function(){
setInterval(function(){
$("#yellow .member").toggleClass("myclass");
},1000);
});
.myclass{
background-color:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="red">
<div class="member">A</div>
</div>
<div id="blue">
<div class="member">B</div>
</div>
<div id="yellow">
<div class="member">C</div>
</div>
You can use nested selectors with jQuery:
$('#yellow #member').removeClass('myclass');
Removes .myclass from the #member element inside #yellow.
Also, your HTML isn't valid. You can use an ID only once per document, so change all <div id="member"> ... </div> to <div class="member"> ... </div>. Then the selector passed to jQuery changes to
$('#yellow .member')
What you're after is the .find() method.
$("#yellow").find('#member').removeClass("myclass");
Or children()
$("#yellow").children('#member').removeClass("myclass");
or
$('#yellow>#member'),removeClass("myClass");
EDIT: Also don't have duplicate id's. Use class attribute instead.

Need a more elegant way of finding an element in the dom tree with jQuery

I have a few elements flying around in an element that need to be altered when the window finishes loading ($(window).load...)
When the script loads, I've been struggling to find a more elegant way of finding a string.
Noticeably below, you can also see the rampant re-use of parent and next operators...
I've tried closest but it only goes up the dom tree once (from what I understand) and parents has never really worked for me, but I could be using it wrong.
Ex.
$(window).load( function(){
if($(".postmetadata:contains('Vancity Buzz')").length){
$(this).parent().parent().next().next().next().next('.articleImageThumb img').hide();
}
});
HTML output this runs through looks like this:
<div class="boxy">
<div class="read">
<div class="postmetadata">Vancity Buzz</div>
<div class="articleTitle"></div>
</div>
<div class="rightCtrls"></div>
<div class="initialPostLoad"></div>
<div class="ajaxBoxLoadSource"></div>
<div class="articleImageThumb">
<a href="#">
<img src="image.png" class="attachment-large wp-post-image" alt=""/>
</a>
</div>
</div>
I think you want to do this:
$(".postmetadata:contains('Vancity Buzz')")
.closest('.read') //Closest will get you to the parent with class .read
.siblings('.articleImageThumb').hide(); //this will get you all the siblings with class articleImageThumb
this refers to window there not the element you are checking in the if condition.
Fiddle
I don't know if your intention is to have the empty anchor tag just by hiding the image. if so just add a find to it.
You can just do this
$('.articleImageThumb img').toggle($(".postmetadata:contains('Vancity Buzz')").length)
If there are multiple divs and you do need to traverse then there are multiple ways
$(".boxy:has(.postmetadata:contains('Vancity Buzz'))").find('.articleImageThumb img').hide()
or
$('.postmetadata:contains("Vancity Buzz")').closest('.boxy').find('.articleImageThumb img').hide()
or
$(".boxy:has(.postmetadata:contains('Vancity Buzz')) .articleImageThumb img").hide()
Have you looked into parents http://api.jquery.com/parents/ you can pass a selector like so:
$(this).parents('.boxy').find(".articleImageThumb")
Careful though, If there is a parent boxy to that boxy, parents() will return it and thus you find multiple .articleImageThumb.

I need the jquery to reach this nested div

I can't figure out how to reach a nested div from the outer most element. Here is the html:
<li id="slide1">
<div id="video-container">
<div id=video-holder><div id="thumbnail"></div></div>
<div id=video-title></div>
<div id=video-desc></div>
</div>
</li>
I need jquery that will reach the id thumbnail from the starting id of the slide1
Use find to get the descendant.
$("#slide1").find("#thumbnail")
Basically since it is id you can just do: as id is supposed to be unique no matter where it appears.
$("#thumbnail");
For your scenario you want to use startswith selector to select the dynamic id starts with video_fake and in the 5th
slide.
$('#slide5fake').find('[id^=video_fake]').attr('id', 'newId')
$("#slide1").find("#thumbnail")
try this
<li id="slide1">
<div id="video-container">
<div id=video-holder><div class="thumbnail"></div></div>
<div id=video-title></div>
<div id=video-desc></div>
<div id="video-container">
<div id=video-holder><div class="thumbnail"></div></div>
<div id=video-title></div>
<div id=video-desc></div>
</div>
</li>
<script type="text/javascript">
$('#slide1').find('.thumbnail').each(function(){ });//you can get here two thumbnail
</script>
$("#thumbnail")
will find the thumbnail directly, but I suspect the id for your thumbnail will be repeated down the page, so you really need to be searchind for a class.
$("#slide1.thumbnail")
will do that if you change this line
<div id=video-holder><div id="thumbnail"></div></div>
to this
<div id=video-holder><div class="thumbnail"></div></div>
In case there are more "thumbnails" on your page, it would be better to give it a class. Ids should be unique.
In your given case, it would be sufficient to get it by ID
document.getElementById("#thumbnail")
If you gave it a class
document.querySelector("#slide1 .thumbnail")
would get you the element.
In jQuery the equivalent would be:
$("#slide1").find(".thumbnail");
There are many ways you can do this...
Single selector:
$('#slide1 #thumbnail');
If you already have the slide element:
var slide = document.getElementById("slide1");
// and then:
$('#thumbnail', slide);
Doing a .find() on the #slide1 element
$("slide1").find("#thumbnail");
But since you're using an ID it doesn't make sense to do anything else but finding that single ID, since you shouldn't have more than one element on a page with the same ID
$("#thumbnail");
There are probably more ways.. and what the best method is depends a lot on what you're doing and what the context is...
Good luck

How to find a parent with a known class in jQuery?

I have a <div> that has many other <div>s within it, each at a different nesting level. Rather than give every child <div> an identifier, I rather just give the root <div> the identifier. Here’s an example:
<div class="a" id="a5">
<div class="b">
<div class="c">
<a class="d">
</a>
</div>
</div>
</div>
If I write a function in jQuery to respond to class d and I want to find the ID for its parent, class a, how would I do this?
I cannot simply do $('.a').attr('id');, because there are multiple class as. I could find its parent’s parent’s parent’s ID but that seems of poor design, slow, and not very polymorphic (I would have to write different code for finding the ID for class c).
Assuming that this is .d, you can write
$(this).closest('.a');
The closest method returns the innermost parent of your element that matches the selector.
Pass a selector to the jQuery parents function:
d.parents('.a').attr('id')
EDIT Hmm, actually Slaks's answer is superior if you only want the closest ancestor that matches your selector.
You can use parents() to get all parents with the given selector.
Description: Get the ancestors of each
element in the current set of matched
elements, optionally filtered by a
selector.
But parent() will get just the first parent of the element.
Description: Get the parent of each
element in the current set of matched
elements, optionally filtered by a
selector.
jQuery parent() vs. parents()
And there is .parentsUntil() which I think will be the best.
Description: Get the ancestors of each
element in the current set of matched
elements, up to but not including the
element matched by the selector.
Extracted from #Resord's comments above. This one worked for me and more closely inclined with the question.
$(this).parent().closest('.a');
Thanks
<div id="412412412" class="input-group date">
<div class="input-group-prepend">
<button class="btn btn-danger" type="button">Button Click</button>
<input type="text" class="form-control" value="">
</div>
</div>
In my situation, i use this code:
$(this).parent().closest('.date').attr('id')
Hope this help someone.
Use .parentsUntil()
$(".d").parentsUntil(".a");

What's the jquery selector for excluding nested descendents?

Per my SO question here, which has turned to jquery to solve this, but which may be worked back into YUI if I get my thinking straight, I need a selector to exclude descendents.
The solution proposed says something like this:
$( '.revealer:not(.revealer > .revealer)' );
To fit more accurately with my situation, because I have multiple HTML chunks to perform the same test on, I have updated it be:
$( '#_revealerEl_0 .handle:not(#_revealerEl_0 .reveal .handle)' );
The HTML its selecting on (image there are numerous copies of this same chunk on a page, each needing to be treated alone - an id attribute is assigned to each 'revealer'):
<div class="revealer" id="#_revealerEl_0">
<div class="hotspot">
<a class="handle" href="javascript:;">A</a>
<div class="reveal">
<p>Content A.</p>
</div>
<div class="reveal">
<p>Content B.</p>
<!-- nested revealer -->
<div class="revealer">
<div class="hotspot">
<a class="handle" href="javascript:;">A</a>
<div class="reveal">
<p>Sub-content A.</p>
</div>
<div class="reveal">
<p>Sub-content B.</p>
</div>
</div>
</div>
</div>
</div>
</div>
In a nutshell: I need to target 'top level' handles within a 'hotspot', per revealer - and no nested descendents with the same class names.
thanks,
d
EDIT:
It's also quite important that I don't start relying on descendant properties like parentNode, childNode[x], nextSibling, etc ... because currently this module is quite flexible in that its 'reveal' and 'handle' elements can reside within other markup and still be targeted - so long as they're found inside a 'hotspot'.
I don't know which is your #_revealerEl_0 element, but if it's your top-level .revealer, can't you just do this?
$('#_revealerEl_0 > .hotspot > .handle')
Or if the top-level .revealer is itself a descendant of #_revealerEl_0, then this works:
$('#_revealerEl_0 > .revealer > .hotspot > .handle')
The basic premise here is that you chain multiple > child combinators.
This works for me using jQuery:
$('.revealer:first > .hotspot > .reveal')
Given the first revealer, find any hotspots that are DIRECT children, and find any DIRECT reveal items within.
So, to assign handlers to your 'handles':
$('.handle').click(function(){
$(this).closest('.hotspot > .reveal').show();
});
The above translates to:
For any given handle, assign a click event function to the element
When a handle is clicked, find its closest parent hotspot
From the hotspot, find any reveal elements that are direct children of the hotspot
Show those elements if they were hidden with display: none.
Try this:
obj = $('.revealer[id*="revealerEl"]');
//this will give you what you are after
result = $("> .hotspot > .handle",obj)
//if you want to see them in red
$("> .hotspot > .handle",obj).css('color','red');
//or assign a click to it
$("> .hotspot > .handle",obj).click(function(){
//blah ....
})

Categories