Get Text Of Closest Parent H4 Using Jquery - javascript

I have several of these html blocks on a page in this structure
<div class="listing">
<h4>Some test Entry here</h4>
<div class="entry clearfix">
<a href="#" class="btn">
Text Here
</a>
</div>
</div>
I have the click event on the '.entry .btn' which is firing fine. But I want to get the inner text of the 'H4 a' within the same listing block as the btn I clicked. I have tried the following but just cannot seem to get the H4 text.
var getTitle = $(this).parents("h4").first();
alert(getTitle.html());
I have also tried closest() but still cannot get the H4? Any ideas?

closest & parents looks for ancestors. But, h4 is in another children of parent .listing.
Try:
var getTitle = $(this).closest('.listing').find("h4").first();

Firstly You need to traverse upwards in the DOM structure to identify the target element using .parent() or .parents() functions.
For your requirement you dont need the immediate parent hence .parent() is of no use instead you need to use .parents() to get all the ancestors in the DOM and refer the one with class selector .listing & finally traverse inward to find the target element h4.
JS CODE:
$('.btn').on('click',function(){
alert($(this).parents('.listing').find('h4').html());
});
Live Demo # JSFIDDLE
Happy Coding :)

use prev function in jquery
var getTitle = $(this).prev().find("h4").first();
alert(getTitle.html());

Related

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');

Delete only the particular Div Id

<div id="#("Bottomgrid)" class="dgd2"></div>
var element = document.getElementById("#Bottomgrid");
element.empty();
$('.dgd2').empty()
Instead of deleting only Bottom grid its also removing other Div present in the screen.
jQuery .remove() will remove the set of matched elements from the DOM.
While jQuery .empty() will remove all child nodes of the set of matched elements from the DOM.
Considering if you have your HTML as below :
<div id="Bottomgrid" class="dgd2"></div>
and you want to remove div with id="Bottomgrid"
Then your javascript code will be :
$("#Bottomgrid").remove();
//This is not required as far as I see
//$('.dgd2').empty()
If you have a HTML structure like this:
<div class="holder">
<div id="item1">Hey</div>
</div>
you can simply just use this pure JavaScript code to remove the "item1" element:
var element = document.getElementById("item1");
element.parentNode.removeChild(element);
.empty() doesn't remove element it only removes elements children. use $('#Bottomgrid').remove()
Javascript :
document.getElementById("Bottomgrid").remove();
Jquery:
$( "#Bottomgrid" ).remove();
you should give the div name properly like Below how I am writing the Id. also you need to check properly which div you are going to delete. Because if a nested div present in your page and you are going to delete the div which is having all the child div inside that , then all respective div going to be deleted .
Html
<div id="bottomgridDiv" class="dgd2">
<div id="parentDiv" class="dgd2">
<div id="childDiv" class="dgd2">
</div>
</div>
</div>
Javascript
var element = document.getElementById("#bottomgridDiv");
In JQuery:-
$("#bottomgridDiv").remove();
So now if you wants to delete the bottomgridDiv then what ever the div present inside this is going to delete.

JavaScript equivalent to JQuery .next()

Is there a JavaScript method similar to jQuery .next()? I want to find the next element that has the class of "error" relative to the element. I've tried using .nextSibling as a loop but couldn't figure it out. Didn't know if there was an easier way to go about it without jQuery.
For instance, if I have this code:
<div id="section">
<div id="test">test</div>
<span class="info">Information</span>
<span class="error">Error!</span>
</div>
I'm trying to get the next .error class closest to #test, if I have a #section2 and a #test2 I would want to get the .error class closest to #test2 and so on.
The nextElementSibling property returns the element immediately following the specified element, in the same tree level.
Example: Get the HTML content of the next sibling of a list item:
var x = document.getElementById("item1").nextElementSibling
The nextElementSibling property might help.
Best bet would be to search through the jQuery code and see what they did.
http://code.jquery.com/jquery-2.0.3.js
At a glance, I do see some calls to "nextSibling" and "previousSibling."
Also see here:
How to get next element using JavaScript-only?
Hope this helps!
This is the pure javascript for you:
HTML
<div id="nodes">
<div class="error">This is error Node</div>
<div class="nextElement">This is next Element</div>
</div>
Javscript:
var nodes = Array.prototype.slice.call( document.getElementById('nodes').children ),
errorNode = document.getElementsByClassName('error')[0];
var indexOfError = nodes.indexOf(errorNode);
var nextElement = nodes[indexOfError + 1];
alert(nextElement.innerText);
Here is demo
Sounds like you may be looking for document.getElementsByClassName()... if the elements with class=error are not direct siblings in the DOM, then there's not a good way to find them otherwise. It's elementary, but you can just search through the array returned by document.getElementsByClassName('error') until you find your starting element, and then you know the next item in the array will be the next element in the DOM.
See also MDN reference. Won't work in old IE, but works for all modern browsers.

Add class to parent div

I am working with the google maps drawing manager. They don't put id's or class names on the drawing tools button bar so I'm trying to do this myself.
First I want to remove the circle button which the below works fine, but I want to add my own button so need to add a class name to the parent div "gmnoprint" but google has about 5 div's all with the same class name. I just want to add it to the one where the circle button was found.
<div class=gmnoprint"></div>
<div class=gmnoprint"></div>
<div class=gmnoprint"></div>
<div class=gmnoprint">
<div>
<div> <== This is what I found in my search
<span>
<div>
<img></img>
</div>
</span>
</div>
</div>
</div>
I am able to find the element I want and remove it, but adding a class to its wrapper div is proving a bit difficult for me.
This works for removing the button
$(".gmnoprint").each(function(){
$(this).find("[title='Draw a circle']").remove();
});
This doesn't work.. Just add's the class to all ".gmnoprint" div's
$(".gmnoprint").each(function(){
$(this).find("[title='Draw a circle']").remove().parent().addClass("test");
});
remove() removes the element from the DOM and returns the free-standing jquery object which has no connection to the DOM at all. A call to parent() after calling remove() is incorrect and that likely is the cause for your issue.
Try splitting your statements to:
var toRemove = $(this).find("[title='Draw a circle']");
toRemove.parent().addClass("test");
toRemove.remove();
You can use jQuery insertAfter and out your button after that default button then remove it.
$(".gmnoprint").each(function(){
var defBtn = $(this).find("[title='Draw a circle']");
$('<button class="my-button" />').insertAfter(defBtn);
defBtn.remove();
});
Or use jQuery after like this:
$(".gmnoprint").each(function(){
$(this)
.find("[title='Draw a circle']")
.after($('<button class="my-button" />'))
.remove();
});
You can use child selector to target the elements
$(".gmnoprint > div > div").addClass('myClassName');
At that point you could replace the html of the whole div , or find the span and replace it's inner html. Using html() method you don't need to use remove() as it will replace all contents of the element(s)
$(".gmnoprint > div > div").addClass('myClassName').find('span').html('<newButton>');
API Reference : http://api.jquery.com/child-selector/

How can I get img src and text from distant elements using JQuery?

Could you please lend a hand as I am having some trouble getting the text of a heading and the source of an image element in order to create a list of the item clicked. But I will explain better with some code:
Firstly I have a div element that goes like this:
<div class="main_page_entry">
<div class="main_item_desc">
<img class="main_item_pic" src="blah.jpg" />
<h6>Item Title</h6>
<span class="icon"> <img src="icon.png" /></span><br />
<span class="address">Some address</span>
<p class="item_desc">More blahs and links for description </p>
</div>
<div class="item_controls">
...
<a href="#" class="add_to_list">
<img src="add_icon.gif" />Add to List
</a>
...
</div>
</div>
It consists with a big div containing two smaller. What I want to do is the following: When I click on 'Add to List' link, I would like to get just the text inside and the main_item_pic source in order to create a list item with those two.
So here is my written code so far:
$('a.add_to_list').live('click', function() {
var name = $(this).closest('h6').text();
var source = $(this).closest('.main_item_pic').src;
$('<li class="hide list_entry"><span class="entry_title">'+
name+'</span><button class="remove_entry"></button>'+
'<img class="list_entry" src="'+source+'" /></li>')
.appendTo('#favs_list ul')
.show('slow');
});
Obviously this doesn't work! I've tried different solutions that I read around here like:
var name = $(this).closest('h6').html();
var source = $(this).closest('.main_item_pic').attr('src');
but oh well...no luck so far. Any ideas? Thanks in advance!
Try going back to the top and coming down again along the right DOM branch:
var src = $(this).closest('.main_page_entry') // Back to the top
.find('.main_item_desc .main_item_pic') // And down again.
.attr('src');
The closest method goes up the DOM tree through your ancestors:
Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
So it won't cross over to any of the sibling branches. Then, once you're at the appropriate ancestor, you use find to come back down, find is just like $() but uses the specified element rather than document as the root:
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
The closest method only finds the closest ancestor that matches the selector you pass it. Because the h6 and img you are looking for are not ancestors of the element you are calling it on, it won't find them. What you need is to find the closest element that contains both the element you are searching from and the elements you are trying to find, and use it as an intermediate step in the search:
var name = $(this).closest('.main_page_entry').find('h6').text();
var source = $(this).closest('.main_page_entry').find('.main_item_pic').attr('src');
First off, if this content isn't added dynamically or in a live manner (in other words, if the content is loaded with the original HTML load) then you do not have to use the .live() function.
Also, why are you using .closest()? Couldn't you just do:
<img class="main_item_pic" ref='pic1' src="blah.jpg" />
<a ref='pic1' href="#" class="add_to_list">
<img src="add_icon.gif" />Add to List
</a>
$('a.add_to_list').click(function(){
var ref = $(this).attr('ref');
var src = $("img[ref='" + ref + "']").attr('src');
var name = $('h6 a').text();
});
The method closest() looks for ancestors. Your h6 and img are not ancestors of your link.
Also, I guess you don't want $('h6').html() but $('h6 a').html()

Categories