How am I mis-using closest? - javascript

I have HTML that looks like this
<div id="1053906-cdm-contract-with-city-of-new-orleans-2013-fema" class="contract-container">
<p class="contract-title contract">CDM- Contract with City of New Orleans: 2013-FEMA-3BCD COOPER GT TOWN DIXON CDM SMITH</p>
<p class="contract-description contract">2013-FEMA-3BCD COOPER GT TOWN DIXON CDM SMITH</p>
<div class="mention-text contract"><div class="page">Page 1</div> sometext </div> <br><br>
<div class="mention-text contract"><div class="page">Page 16</div> some text</div> <br><br>
</div>
When a user clicks anywhere in the outer-most div, I want to find the closest "page". I use this jquery
firsthtml = $(this).closest(".page").html();
This returns "undefined" for firsthtml
If I get rid of the .html() and hover over the firsthtml var -- I see that it returns the HTML for the entire div. In other words it returns multiple divs with class="page".
Why isn't it pulling only the first class with "page"?

So there's a difference between .closest() and .find() and what you're trying to do.
http://api.jquery.com/closest/
closest and find navigate up and down the DOM tree. If you wanted to get the HTML of .page you would have to say something like
$(this).find('.page').html();
Since `.page' is almost the last element in your div structure.
If you're looking to get the HTML of the FIRST .page element, that is different. You'd have to say something like:
$('.page').eq(0).html()
.eq() is another way of saying .index() but it will select whichever element you want. If you want to select that page inside that specific div, you could possibly do
$(this).find('.page').eq(0).html();

Related

Get the Count of Input Tags inside a Div Element using the Closest Property Jquery

I know it is a stupid question but i couldn't find a solution for this. Knocking my head for hours.
I have a HTML Structure,
<div class= 'container'>
<div class="someclass">
<input>some content</input>
<input>some content</input>
</div>
<input id="question-xxx" type="hidden"></input>
</div>
I need to get the count of all the Input elements inside the class = 'someclass' using the id = "question-xxx".
I tried using
$("#question-xxx").closest('.someclass').find('input').length;
or
$('#question-xxx').closest('.someclass').children().length;
I googled it out, and I have no clue what I'm doing wrong. Any help would be quite appreciable.
.someclass will not be found using closest try finding it by siblings.
closest is used to find the parent element of given element. Here someclass is not parent of question-xxx.
closest and parent are same. You can find more info here
$("#question-xxx").siblings('.someclass').find('input').length
var count = $('#question-xxx').prev('.someclass').find('input').length;
alert(count)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class= 'container'>
<div class="someclass">
<input>some content</input>
<input>some content</input>
</div>
<input id="question-xxx" type="hidden"></input>
</div>
use .prev() to get the div that contains the input
Description: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.
use .length to count

How to get a div which is removed from the DOM when it's parent has been made .empty()?

I have a div in a HTML file
"<div id="abc" hidden="hidden">
<div id="statIndicator">
<span id="imgInd" class="status-indicator-border">
<img src="../../LibSrc/SharedResources/IMG/loading-trace.gif" />
</span><span id="messageIndicator">Updating Plots...</span>
</div>
</div>"
I insert the statIndicator div in another div using append.
so that div becomes
<div id="parentDiv">
<div id="statIndicator">
<span id="imgInd" class="status-indicator-border">
<img src="../../LibSrc/SharedResources/IMG/loading-trace.gif" />
</span><span id="messageIndicator">Updating Plots...</span>
</div>
</div>
On refresh I write $('#parentDiv').empty() it deletes whatever is inside the 'parentDiv'.
But when I try to append statIndicator using $('#statIndicator'), it return "[]", though I have the 'statIndicator' div in Html.
Is there a way in which I can get the 'statIndicator' div?
No. $.empty() deletes the contents, so your "statIndicator" div no longer exists at all.
Just remove it from "parentDiv" before you call $.empty(). Either store it in a variable or put it back where it started, in "abc".
I think jquery.append() moves the selected elements without making a copy. So you can explicitly create a copy using the .clone() method and append it's result. Something like:
$('#abc #statIndicator').clone().appendTo('#parentDiv');
This is creating a copy and then appending it at the new location.
Once you do this there will be two divs with the same id, so it will be a good idea to always reference the statIndicator's parent container in your selectors.
You can use .detach() function if you want only parentDiv to be removed

Easiest way to get element parent

Suppose i have this structure of elements:
<div class="parent">
<div class="something1">
<div class="something2">
<div class="something3">
<div class="something4"></div>
</div>
</div>
</div>
</div>
And code like this:
$(".something4").click(function(){
//i could do it like this...
$(this).parent().parent().parent().parent().parent();
});
But that seems to be stupid, is there a better way to do this?
also i can't just say $(.parent) because there are many divs like this with class parent in my page.
Use .closest(selector). This gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
$('.something4').click(function() {
$(this).closest('.parent');
});
Use .closest():
$('.something4').click(function() {
$(this).closest('.parent');
});
I think you should try this
$(this).parents(".parent");
But I don't know where on the page are the other divs with this class :)
You could always use .parentNode (standard JavaScript). It's generally a bad idea to use class names that coincide with function/variable names from the library you're using (this goes for any language). Making your class names more unique is a better approach (for instance, "scparent" instead of "parent", if the name of your application was "Super Calculator" or something). This avoids conflicts such as the one you're describing.
I would caution using .closest(), simply because you may create a function like this:
function getParentElem() {
return $(this).closest('div');
}
And it would grab the parent div's in your code just fine, but if down the road you add a table for displaying data, and you run the function through a child element of the table, you will have to create another implementation that selects the table element, because that's what you now want:
<div id="tableParent">
<table id="dataTable">
<tr id="target1">
<td>Some data.</td>
</tr>
</table>
</div>
By using your function getParentElem() on the tr element, you'll end up grabbing the div with id="tableParent", rather than the actual parent, which is the table element. So, unless you've delineated your parent classes appropriately all the way through your code (which can be a pain and isn't always efficient), you may run into problems. Especially if at any point you're creating elements programmatically, or reading in data from another 3rd-party library or script.
Not saying it's not good to use .closest()... just pointing out a possible "gotcha".
i would suggest adding to the div parent an id like 'parent_1' etc. and in every son you keep the id in the rel attr
<div id="parent_1" class="parent">
<div rel="1" class="something1">
<div rel="1" class="something2">
<div rel="1" class="something3">
<div rel="1" class="something4"></div>
</div>
</div>
</div>
</div>
$(".something4").click(function(){
//i could do it like this...
$('#parent_' + $(this).attr('rel'));
});

select a div which is not inside another div jquery

let's say I have an HTML structure like this:
<div class="first">
<div class="sub-1">
<div class="first again"></div>
</div>
</div>
How do I select only the div that has the class "first" but which is NOT inside the div that has the class "sub-1". In order words, how do I get only the outer div but extract any div inside that outter div that have the same class than the outter div (I want to get just the div with class="first", not the one with class="first again").
Thank you
See jQuery documentation for .not(). This should work:
$('.first').not('.sub-1 .first');
I dont know if you mean a very generic way to handle this but in this particular case you can only write.
$(".first:first")
A more generic way would be
$('.first').not('.sub-1 .first').prepend("I was first");
http://jsfiddle.net/JYLVc/

Trying to select a specific node with Dojo

I'm trying to select the text from the name attribute of the anchor element of the last Comment div in the Comments div (i.e. comment_3037) How can I select it?
Here's my html:
<div id="Comments">
<div class="Comment"><!-- last "Comment" element in the div -->
<a name="comment_3037"></a>
<img src="">
<div>
<div class="Stats">Some info goes here</div>
<div class="Body">Comment goes here.</div>
</div>
</div>
</div>
Corrected Version
(dojo.query always returns a nodelist)
This would look something like that:
var nodelist = dojo.query('#Comments > .Comment:last-child > a[name]);'
var value = dojo.attr(nodelist.at(0), 'name');
Explanation: #Comments > .Comment selects all nodes with class Comment inside the node with id Comments. :lastChild reduces this selection to the last child. > a[name] selects all immidiate children of type a with the attribute name.
The second line just gets the value from the name attribute of the node.
You should get the correct element with that, but I haven't tested it.
Have a look at the dojo reference, there are tons of useful functions.
(I don't work at dojo, I just really like it ;) )
Info
http://docs.dojocampus.org/dojo/query
EDIT
To make sure that you get only the node you want (if you add another link with a name attr), you could add a class "thisisthelinkiwant" (or similar ;) ) to the appropiate link and updating the query to 'Comments .thisisthelinkiwant:last-child'.
You might consider reading about css selectors, as they are quite important with this function.

Categories

Resources