How to access child of parent in jQuery - javascript

Trying to get the child of a parent through a child accessor. Basically trying to get the .block__id through the add__block class.
HTML
<div class="col-12">
<span class="block__id">{{$block->id}}</span>
{{$block->title}}
<span class="add__block">+</span>
</div>
jQuery
$(".add__block").click(function(){
$(this).parent().find(function(){
var id = $(".block__id").text();
});
console.log(id);
});
Currently I get id not defined.

Your logic is almost correct, but the issue is that you're providing a function to find() whereas you simply need to use a selector string:
$(".add__block").click(function() {
var id = $(this).parent().find(".block__id").text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
<span class="block__id">Block #1</span>
Block title
<span class="add__block">+</span>
</div>
<div class="col-12">
<span class="block__id">Block #2</span>
Block title
<span class="add__block">+</span>
</div>

I'm not very familiar with jQuery, but with vanilla Javascript this is very easy:
const blocks = document.querySelectorAll('.add__block');
for (const block of blocks) {
block.addEventListener('click', (e) => {
console.log(e.target.previousElementSibling.textContent)
})
}
<div class="col-12">
<span class="block__id">{{$block->id}}</span>
{{$block->title}}
<span class="add__block">+</span>
</div>

Another alternative is just looking for the sibling with prev method, which might be slightly faster than going to parent and then search from there.
$('.add__block').click(function(){
var id = $(this).prev('.block__id').text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
<span class="block__id">Block #1</span>
Block title
<span class="add__block">+</span>
</div>
<div class="col-12">
<span class="block__id">Block #2</span>
Block title
<span class="add__block">+</span>
</div>

Can you try like below:
$(".add__block").click(function(){
var id = $(".block__id").text();
console.log(id);
});

On click you can find the parent of the .add__block element and find the relevant .block__id within the parent as follows,
$(".add__block").click(function(){
console.log($(this).parent().find(".block__id").text(););
});

$('.add_block').prevAll('span')

Related

Remove next element using jQuery

I have the below HTML
<div name="taskNotificationsDiv">
<div class="notificationCard">
<span class="taskNotificationClose">x</span>
Test
</div>
<hr>
<div class="notificationCard">
<span class="taskNotificationClose">x</span>
Test
</div>
<hr>
<div class="notificationCard">
<span class="taskNotificationClose">x</span>
Test
</div>
<hr>
</div>
And I have the below script which when x is clicked removes the container from the parent.
$(".taskNotificationClose").click(function (){
this.parentNode.parentNode
.removeChild(this.parentNode);
return false;
});
What I am looking for is also removing the hr which is below the div container..Can someone please have a look and let me know how it can be done.
Here's the fiddle [Fiddle][1]
I tried with the below code to find nearest hr and remove it from the parent but it's throwing an error
var $hr = $(this).next('hr');
this.parentNode.parentNode.removeChild($hr);
Thanks
[1]: https://jsfiddle.net/so3k2hpq/
You can use .next() function. A better approach to solve the problem with JQuery:
$(".taskNotificationClose").click(function (){
$(this).parent().next("hr").remove();
$(this).parent().remove();
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div name="taskNotificationsDiv">
<div class="notificationCard" style="color:red;">
<span class="taskNotificationClose">x</span>
Test
</div>
<hr>
<div class="notificationCard" style="color:blue;">
<span class="taskNotificationClose">x</span>
Test
</div>
<hr>
<div class="notificationCard" style="color:green;">
<span class="taskNotificationClose">x</span>
Test
</div>
<hr>
</div>
You can move 'hr' tag inside each div. It will solve your problem.
JQuery .next(element) can do this
$(".taskNotificationClose").click(function (){
$(this).parent().next("hr").remove();
$(this).parent().remove();
return false;
});
The reason for your earlier error, is that you removed the first sibling first before calling .next()

Link simillary name classes so that when one is clicked the other is given a class

Basically, I'm asking for a way to optimize this code. I'd like to cut it down to a few lines because it does the same thing for every click bind.
$("#arch-of-triumph-button").click(function(){
$("#arch-of-triumph-info").addClass("active-info")
});
$("#romanian-athenaeum-button").click(function(){
$("#romanian-athenaeum-info").addClass("active-info")
});
$("#palace-of-parliament-button").click(function(){
$("#palace-of-parliament-info").addClass("active-info")
});
Is there a way to maybe store "arch-of-triumph", "romanian-athenaeum", "palace-of-parliament" into an array and pull them out into a click bind? I'm thinking some concatenation maybe?
$("+landmarkName+-button").click(function(){
$("+landmarkName+-info").addClass("active-info")
});
Is something like this even possible?
Thanks in advance for all your answers.
EDIT: Here's the full HTML.
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button"></div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button"></div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Assuming you're not able to modify your HTML markup (in which case with use of CSS classes would be cleaner), a solution to your question would be as shown below:
// Assign same click handler to all buttons
$("#arch-of-triumph-button, #romanian-athenaeum-button, #palace-of-parliament-button")
.click(function() {
// Extract id of clicked button
const id = $(this).attr("id");
// Obtain corresponding info selector from clicked button id by replacing
// last occurrence of "button" pattern with info.
const infoSelector = "#" + id.replace(/button$/gi, "info");
// Add active-info class to selected info element
$(infoSelector).addClass("active-info");
});
Because each .landmark-button looks to be in the same order as its related .landmark-info, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
Live snippet:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
.active-info {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button">click</div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button">click</div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button part of it, and then select it concatenated with -info:
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.

How to find a particular grand parent by Id and get value of its particular children by certain class using jQuery

I have a dynamic div
<div class="illustartionWrap" id="illustartionWrapId">
<div class="illusList illusListTop" id="illusList_heading">
<span class="fileName">File Name</span>
<span class="fileDesc">Description</span>
<span class="fileSize">File Size</span>
<span class="fileDownload">Download</span>
</div>
<div class="clear"></div>
<div class="illusList">
<span class="fileName">fileTitle</span>
<span class="fileDesc">fileDesc</span>
<span class="fileSize">1.18 MB</span>
<span class="fileDownload">
<a href="http://myfile/file.txt">
<img src="/sites/all/themes/petheme/images/myimage.png">
</a>
<a href="#">
<img id="illFile_6" class="illDeleteFile" src="/sites/all/themes/petheme/images/icons/deleteButton.png">//clicking it to delete the file from db
</a>
</span>
</div>
</div>
How to get the parents of this delete button and find the filetitle class to get the title of the file.
Below is click handler which I wrote
/**delete function for my page**/
jQuery(".illDeleteFile").on("click", function() {
var illDeleteId = jQuery(this).attr("id").split("_");
var illFileTitle = jQuery(this).parent("#illusList").children(".fileName").val();
alert (illFileTitle);
});
I checked with jQuery Parent() , Parents() and children() and also find() but I am getting undefined mostly and not getting the title.
How to achieve this?
JSFIDDLE : http://jsfiddle.net/hiteshbhilai2010/ywhbd9ut/14/
See this,
jQuery(".illDeleteFile").on("click", function() {
var illFileTitle =jQuery(this).closest(".illusList").find(".fileName").html();
alert (illFileTitle);
});
You'll want to use:
var illFileTitle = jQuery(this).closest(".illusList").find(".fileName").text();
alert(illFileTitle);

Jquery find and each selector

I am new to jQuery so please help me with the output.
Below is the HTML code used for reference.
<html>
<body>
<div id="level1">
<p>
<span id="level1.1">
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
</span>
<span id="level1.2">
<div id="level1.2.1"></div>
<div id="level1.2.2"></div>
</span>
<div id="level1.3"></div>
</p>
</div>
</body>
</html>
When I used following as script
<script type="text/javascript">
$(document).ready(function (){
var div = $("#level1").find("div").each(function(){
alert($(this).attr('id'));
});
});
</script>
The result was 5 alerts with id of each div
But when I used
<script type="text/javascript">
$(document).ready(function(){
var div = $("#level1").find("span > div").each(function(){
alert($(this).attr('id'));
});
});
</script>
There were only two alert for level 1.2.1 and 1.2.2
I was wondering why there was no alert for 1.1.1 and 1.1.2 as they also have span as their parents?
Thanks in advance.
If divs can't be child of
then why is
<p>
<div id="level1">
<span id="level1.1">
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
</span>
<span id="level1.2">
<div id="level1.2.1"></div>
<div id="level1.2.2"></div>
</span>
<div id="level1.3"></div>
</div>
</p>
Working fine ??
Because of your incorrect HTML.
The browser is going to generate your html as followed.
<p>
<span id="level1.1">
</span>
</p>
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
Because a div can't be a child of a p
If you remove the first <p> in your code, you wil get an alert of the 4 levels sub levels.
divs cannot be children of p in HTML
Change your HTML markup with the following:
<div id="level1">
<span id="level1.1">
<div id="level1.1.1"></div>
<div id="level1.1.2"></div>
</span>
<span id="level1.2">
<div id="level1.2.1"></div>
<div id="level1.2.2"></div>
</span>
<div id="level1.3"></div>
</div>
and you should yield the expected results !
Because your HTML structure is not correct this how your structure is populated :
.find() method only travels a single level down the DOM tree.
Here you can find it.
The .find() and .children() methods are similar, except that the .find() method only travels a single level down the DOM tree.

Get Parent ID of this DIV

I am looking to find the parent div id (i.e. "Bakerloo") from this layout when the button is clicked within ".buttonleft0" in jquery / javascript.
<div id='Bakerloo' class='box'>bakerloo<p></p><span class='buttons'>
<span class='buttonleft0'><button onClick='up()'><span class='icon icon10'></span>
</button>
</span><span class='buttonleft'></span><span class='buttonright'></span></span>
<div class='comingup'></div>
<div class='more'></div></div>
I have tried:
$(this).parent('id');
But this just returns 'undefined'.
$(this).closest('div').attr('id')
I think this is what you want
The parent() function returns the jQuery object, so you need to use the attr() for any of it's attributes like so:
$(this).closest().attr('id');
Edit: On further inspection it appears the button isn't the direct child of the div, and so use of the closest() function would be required.
Straight up Javascript always works for me.
<div id='Bakerloo' class='box'>
bakerloo<p></p>
<span class='buttons'>
<span class='buttonleft0'>
<button onClick='alert(this.parentNode.parentNode.id)'>
<span class='icon icon10'></span>
</button>
</span>
<span class='buttonleft'></span>
<span class='buttonright'></span>
</span>
<div class='comingup'></div>
<div class='more'></div>
</div>
Try this:
$(this).parent().attr("id");
Your code itself have few errors so here is the correct one:
HTML
<div id='Bakerloo' class='box'>bakerloo<p></p><span class='buttons'>
<span class='buttonleft0'><button><span class='icon icon10'>Click here</span>
</button>
</span><span class='buttonleft'></span><span class='buttonright'></span></span>
<div class='comingup'></div>
<div class='more'></div></div>
JQuery
jQuery(document).ready(function($){
$("button").on('click',function(){
alert($(this).closest('div').attr('id'));
});
});
here is the fiddle http://jsfiddle.net/cpeeyush/ydk4e/
Try this:
$(this).closest('div[id]')
alert($(this).parent().id);
If you want to be sure to select correct class, try:
alert($(this).parent('.div').id);
If you have a deeper hierarchy you can use:
alert($(this).parents('.div:eq(n)').id);
where n is which parent you want to get

Categories

Resources