find attribute value using closest function - javascript

I have tried this but didn't know whats wrong with it. Results undefined
$(document).ready(function() {
$("img").click(function(event) {
var test = $(this).parent('.parentClass').closest('.headingLink').attr('href');
console.log("testing this", test);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parentClass">
<div class="link__img">
<img alt="ffdbb" class="article-link__imgSrc" src="img.jpg" />
</div>
<div class="content">
<a class="headingLink" target="jakfhaf" alt="somethingf" href="www.google.com">
<h4>some head</h4>
</a>
<p>hdgajsfjghasjfh</p>
</div>
</div>

.closest() traverse up the DOM tree. What you are looking for is .find(). Also you are using .parent() which traverses up one level. Use .closest() instead.
$(document).ready(function() {
$("img").click(function(event) {
var test = $(this).closest('.parentClass').find('.headingLink').attr('href');
console.log("testing this", test);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parentClass">
<div class="link__img">
<img alt="ffdbb" class="article-link__imgSrc" src="img.jpg" />
</div>
<div class="content">
<a class="headingLink" target="jakfhaf" alt="somethingf" href="www.google.com">
<h4>some head</h4>
</a>
<p>hdgajsfjghasjfh</p>
</div>
</div>

You can use parents instead of parent and use find to get the child.
.parents() - Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
.find() - Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
Example:
$(document).ready(function() {
$("img").click(function(event) {
var test = $(this).parents('.parentClass').find('.headingLink').attr('href');
console.log("testing this", test);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parentClass">
<div class="link__img">
<img alt="ffdbb" class="article-link__imgSrc" src="img.jpg" />
</div>
<div class="content">
<a class="headingLink" target="jakfhaf" alt="somethingf" href="www.google.com">
<h4>some head</h4>
</a>
<p>hdgajsfjghasjfh</p>
</div>
</div>

closest() is just for searching in parents not in childrens. You're searching in childrens so use find() instead of closest().

parent([selector]) only traverses up one level, and closest(selector) only traverses up. Instead, I think you should use closest('.parentClass') and then use closestParentClass.find('.headingLink').
Edit: #Kalimah has a more detailed (with code) explanation.

$(document).ready(function() {
$("img").click(function(event) {
var test = $(this).closest('.parentClass').find('.headingLink').attr('href');
console.log("testing this ", test);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parentClass">
<div class="link__img">
<img alt="ffdbb" class="article-link__imgSrc" src="img.jpg" />
</div>
<div class="content">
<a class="headingLink" target="jakfhaf" alt="somethingf" href="www.google.com">
<h4>some head</h4>
</a>
<p>hdgajsfjghasjfh</p>
</div>
</div>

The .closest and .find selectors are complements of each other and
used together are the best way to get to the corresponding element of
where the click (or any event) occurred.
The .closest selector traverses up the DOM to find the parent that
matches the conditions where as the .find selector traverses down
the DOM where the event occurred, that matches the conditions.
var test = $(this).closest('.parentClass').find('.headingLink').attr('href');
Replacing your code with this line of code should work for your problem.

Related

How to check if inner <div> has text

what I'm trying to do is to check if my inner <div> has a text for example Ended and then remove if it has a text. I have multiple <div> with the same class name. I tried using .filter(). I would like to remove the div container_one that contains the found element.
Here is my HTML:
var $filstatus = $('.status').filter(function() {
return $(this).text() == 'Ended';
});
$filstatus.remove();
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
Thank you for the help!
I would use the jQuery's selector by content
combined with .closest(). This might be the shortest way:
$('.status:contains("Ended")', $('.main_container')).closest('.container_one').remove();
First ('.status:contains("Ended")') will select all elements that have a class status, contain the text "Ended" and are children of main_container (not needed but is recommended to speed up selection of elements on complex pages).
Then the method .closest('container_one') will climb up the parents tree for each of the elements from the previous step and select the first parent element with class 'container_one'.
At last it will remove all elements found.
Note: all those methods work both with single element and collections of elements, so no need of any for/foreach.
Working JSFiddle Demo
Pure JavaScript solution with forEach:
var div = document.querySelectorAll('.container_one');
div.forEach(function(el){
var target = el.querySelector('.status');
if(target.textContent == 'Ended'){
el.remove();
};
})
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
Try this
$filstatus.parent().parent().remove();
filter will return an array , then use each to loop over that and delete the element. In this case it will remove that specific div but the parent div will still be in dom
var $filstatus = $('.status').filter(function() {
return $(this).text().trim() === 'Ended';
});
$filstatus.each(function(index, elem) {
$(elem).remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
If you want to remove .container_one whose inner child has the text Ended, try
const ended = $('.status').filter((index, element) => $(element).text() === 'Ended')
ended.parents('.container_one').remove()
Since you want to remove the closest ansistor with class .container_one, you will need to use closest
$filstatus.closest(".container_one").remove();
Check this: https://jsfiddle.net/n3d5fwqj/1/
https://api.jquery.com/closest/
Try using this if you don't need $filstatus in other places
$('.status').each(function(){
if ($(this).text() == "Ended"){
$(this).parent().parent().remove();
}
})
I see your problem is you are able to remove the child div status but what you want is to remove the entire parent div with class container_one
you can use $.each for that and use closest(class_name) to remove the parent including its child
$.each($('.status'), function(idx, div) {
if ($(this).text() == 'Ended') {
$(this).closest('.container_one').remove();
}
});
Demo
or you can continue your filter and just add .closest('.container_one') to your jquery selector
var $filstatus = $('.status').filter(function() {
return $(this).text() == 'Ended';
});
$filstatus.closest('.container_one').remove();
Demo

How to select this element with jQuery?

I have this piece of HTML code.
<div class="row member-item">
<div class="col-md-3"><img src={{ i.mem_imgurl }}></div>
<div class="col-md-2">姓名<br><div class="mem_name">{{ i.mem_name }}</div></div>
<div class="col-md-2">组别<br><div class="mem_group">{{ i.mem_group }}</div></div>
<div class="col-md-2">年级<br><div class="mem_year">{{ i.mem_year }}</div></div>
<div class="col-md-1"><button class="btn btn-danger btn-sm deleteNode" onclick="delNode(this)">Delete</button></div>
</div>
And I write js as follows,
function delNode(btn) {
var mem_item = $(btn).parent().parent();
var mem_name = $(mem_item).children("div.mem_name").text();
alert(mem_name);
console.log(mem_name);
mem_item.hide()
}
I want to get the text value of div.mem_name, but somehow it just does not work:(
The children function only travels down the immediate children of the element. You can use find to search down the tree of children. This should work:
var mem_name = $(mem_item).find("div.mem_name").text();
This is from the jQuery children() documentation:
The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.
Similarly, your parent().parent() call can be replaced with closest() or parents():
var mem_item = $(btn).parents(".member-item");
You can use .closest and .find together
Script :
$(document).ready(function(){
$(".deleteNode").click(function(){
var mem_name = $(this).closest('.row').find('.mem_name').text();
alert(mem_name);
console.log(mem_name);
});
});
HTML :
<div class="row member-item">
<div class="col-md-3"><img src=""></div>
<div class="col-md-2">姓名<br><div class="mem_name">name</div></div>
<div class="col-md-2">组别<br><div class="mem_group">mem_group</div></div>
<div class="col-md-2">年级<br><div class="mem_year">mem_year</div></div>
<div class="col-md-1"><button class="btn btn-danger btn-sm deleteNode" >Delete</button></div>
</div>
JSFIDDLE DEMO

jQuery closest class selector

<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
jQuery
$('.Level2').click(function(){
$('.Level2').closest('.Level3').fadeToggle();
});
I wanted to select the closest level3 to fadeIn and fadeOut, but doesn't work. Is my syntax wrong? online Sample :http://jsfiddle.net/meEUZ/
Try .next() instead of .closest() that traverses through the ancestors of the DOM element.
Working Demo
Also you should use $(this) rather than $('.Level2') else it'll select ALL the .Level2 rather than the clicked one.
You can also go for something like this - $(this).closest('.wrap').find('.Level3').fadeToggle();.
jQuery's .closest() method doesn't select sibling selectors, but parents. Looks like you're looking for the .siblings() method.
$('.Level2').click(function(){
$(this).siblings('.Level3').fadeToggle();
});
closest travels up the dom tree. it won't find something thats a sibling. you can use a find on a parent to achieve this
$('.Level2').click(function(){
$(this).parent().find('.Level3').fadeToggle();
});
Yes, There are many method avaiable in Jquery to find closest of the DOM element
$('.Level1').click(function(){
$(this).next('.Level3').fadeToggle();
});
$('.Level2').click(function(){
$(this).closest('.wrap').find('.Level3').fadeToggle();
});
$('.Level4').click(function(){
$(this).parent().find('.Level3').fadeToggle();
});
$('.Level5').click(function(){
$(this).siblings('.Level3').fadeToggle();
});
.level{background:Red;width:200px;height:40px;}
.Level3{background:blue;width:300px;height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="Level1 level">Click me()sing next)</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2 level">Click me(Using closest)</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level4 level">Click me(Usingh Parent)</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level5 level">Click me(Using Sibiling)</div>
<div class="Level3">Information</div>
</div>
Yes! closest starts the DOM search from the selector you pass to it, and goes upwards the DOM hierarchy, searching through the parents/ancestors. Use siblings or next instead.
Like this:
$('.Level2').click(function(){
$(this).siblings('.Level3').fadeToggle();
});
Get a clear idea from the following code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(".add").on("click", function () {
var v = $(this).closest(".division").find("input[name='roll']").val();
alert(v);
});
});
</script>
<?php
for ($i = 1; $i <= 5; $i++) {
echo'<div class = "division">'
. '<form method="POST" action="">'
. '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
. '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
. '</form></div>';
}
?>

JQuery: How to find out how many children an element has?

How can I use jQuery to find out how many children an element has?
Say I have the following structure:
<div id="container">
<div id="column1">
<div id="asset1"></div>
<div id="asset2"></div>
</div>
<div id="column2">
<div id="asset1"></div>
<div id="asset2"></div>
</div>
</div>
I want to find out how many children the div element: container, has. In this case it would return 2...
Use children and length:
$("#container").children().length
Use the direct children selector (>) and the length property:
$('#container > *').length
Example - http://jsfiddle.net/TtV8d/

jquery : dynamic events how to achieve

What is the best way to do this dynamic events linking between divs in jquery.
my HTML page:
<html>
<body>
<div id="parent1"></div>
<div id="parent2"></div>
<div id="parent3"></div>
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</body>
</html>
for each clicked parent i want to .toggle its child
Example :: if parent2 clicked, .toggle will be applied on child2 only
my parents and childs divs are dynamically created so their number is not static, i think .live should be used here, but i have no idea how to achieve that.
Thanks
This should do it, using the rel attribute to note link. You could also do the same thing by parsing the ID and so on, but I find this solution more semantic (if it means something) :
<html>
<body>
<div id="parent1" class="parents" rel="child1"></div>
<div id="parent2" class="parents" rel="child2"></div>
<div id="parent3" class="parents" rel="child3"></div>
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</body>
</html>
jQuery(function(){
jQuery(".parents").live("click", function(){
jQuery("#"+jQuery(this).attr("rel")).toggle();
});
});
This will work with your current structure (another option is to extract the number, same general idea):
$("[id^=parent]").live('click', function(){
var childId = this.id.replace('parent', 'child');
$('#' + childId).toggle();
});
Using the startsWith selector and slightly modded ID values, because the underscore character eliminates the need for a regex:
<div id="parent_1" class="parents"></div>
<div id="parent_2" class="parents"></div>
<div id="parent_3" class="parents"></div>
<div id="child_1"></div>
<div id="child_2"></div>
<div id="child_3"></div>
$("div[id^=parent]").click(function() {
$('#child_' + $(this).attr('id').split('_')[1]).toggle();
});
I also like #Kobi's approach.
Use a class for these divs and use the class selector.
$(".divclass").live ( "click" , function() {
$(this).find("yourchildelementselector").toggle();
});
If its a parent child relation then better put the child divs inside the parent element.
<div id="parent1" class="parent"><div id="child1" class="child"></div></div>
<div id="parent2" class="parent"><div id="child2" class="child"></div></div>
<div id="parent3" class="parent"><div id="child3" class="child"></div></div>
and you can call the click event as
$("div.parent").live ( "click" , function() {
$(this).find("div.child").toggle();
});

Categories

Resources