How to find element of div from another div - javascript

I have the elements in the div as mentioned below:
<div id="container">
<div id="first_div">
<div id="comment-1" class="comment">Child 1 of first div</div>
<div id="comment-2" class="comment">Child 2 of first div</div>
<div id="comment-3" class="comment">Child 3 of first div</div>
<div id="comment-4" class="comment">Child 4 of first div</div>
</div>
<div id="second_div">
<div id="comment-5" class="comment">Child 1 of second div</div>
<div id="comment-6" class="comment">Child 2 of second div</div>
<div id="comment-7" class="comment">Child 3 of second div</div>
<div id="comment-8" class="comment">Child 4 of second div</div>
</div>
<div id="third_div">
<div id="comment-9" class="comment">Child 1 of third div</div>
<div id="comment-10" class="comment">Child 2 of third div</div>
<div id="comment-11" class="comment">Child 3 of third div</div>
<div id="comment-12" class="comment">Child 4 of third div</div>
</div>
I need to retrieve the next element from comment id comment-4.
$('#comment-4').next().attr('id') gives me result as undefined.I need the target div to be comment id - comment-5.How to retrieve the next element of div from another div using jquery?

Try this :
$(function(){
$('.comment').click(function(index){
var id;
if ( $(this).is(':last-child') )
id = $(this).parent().next().children(':first').attr('id');
else
id = $(this).next().attr('id');
alert(id);
});
});
Demo

Demo : http://jsfiddle.net/abdennour/PU54r/
function nextOf(id,cyclic){
var ids= $('div[id^=comment-]').toArray().map(function(e){return $(e).attr('id')}).sort();
var idx=ids.indexOf("comment-"+id);
if(idx!==-1){
if(ids.length> idx+1){
return $('div#'+ids[idx]);
}
else{
// it is the last div: if it is cyclic ,you may return the first
if(cyclic){
return $('div#'+ids[0]);
}
}
}else{
// no div with this id
}
}
Then :
var target=nextOf(4)
if(target){
target.html()
//--> Child 1 of second div
}

I think you can use $('.comment') to pick up all of your wanted, and save them in some variable such as var arrResult = $('.comment');.
So far, you can choose what you wanted use the arrResult variable.

Because your inner-most divs have different parents, I would first get all the divs you care about:
var comments = $('.comment');
Next, if we can assume your id's are all numbered sequentially, get the number in the id (assuming this references the element):
var index = parseInt($(this).attr('id').substr(8));
Now, the next div in the comment list is at that position in the comments:
var nextDiv = comments[index];
Just for good measure, I'd first make sure index is set:
var nextDiv;
if (index < comments.length) {
nextDiv = comments[index];
}

You could use an index in your case :
JS:
for (var index = 0; index <= 12; ++index) {
$("#comment-" + index).attr("id");
}

You can define a statement which checks the target id is the last child, than you can return a function according to value.
jsFiddle Demo
var target = 'comment-4';
$('.comment').each(function(i) {
if ( $(this).attr('id') == target ) {
if ( $(this).is(':last-child') ) {
$(this).parent().next().children().first().addClass('red');
}else{
$(this).next().addClass('red');
}
}
});

Here is one way - http://jsfiddle.net/jayblanchard/WLeSr/
$('a').click(function() {
var highlight = $('.highlight');
var currentIndex = $('.comment').index(highlight); // get the index of the currently highlighted item
$('.comment').removeClass('highlight');
var nextIndex = currentIndex + 1;
$('.comment').eq(nextIndex).addClass('highlight');
});

It is showing undefined because comment-4 and comment-5 are childrens of different parent elements. Means comment-4 is children of first_div and second_div parent of comment-5.
You can get the comment-5 using below code.
$('#comment-4').parent().next().children().attr('id');

Assuming jQuery-wrapped element is collected in $comment, there's one way to solve it:
function getNextComment($comment) {
var $nextComment = $comment.next();
if ($nextComment.length) {
return $nextComment;
}
var $nextParent = $comment.parent().next();
if ($nextParent.length) {
return $nextParent.children().first();
}
return null;
}
Demo. Click on one comment - and see the next one's highlighted. )
The base algorithm's very simple here. First, we attempt to retrieve the next sibling of the given element. If there's one, it's returned immediately. If not (and it's the case with #comment-4 in your question - it's the last element in its hierarchy), we go up the DOM chain for its parent (#first-div, in this case), and look for its next sibling (#second-div). If it exists, then its very first child element is returned. If it doesn't, null is returned (we can actually return an empty jQuery object - $(), but that depends on use cases.

Just one instruction : )
$('<div id="mock" />').append($('.comment').clone()).find('#comment-4').next().attr('id')//---> comment-5
Based on divs have the same Css class .comment
DEMO

Why not this will be undefined: $('#comment-4').next().attr('id') because there is no next element. as you mentioned that you want to target the #comment-5 in the next div's child then you can do this:
function giveId(el) {
var sel = el.id ? '#'+el.id : '.'+el.className;
var id = $(sel).next('div').length ? $(sel).next('div').attr('id') : $(sel).parent('div').next('div').find('> div:first').attr('id');
return id || "Either no next elem exist or next elem doesnot have any id/class.";
}
$(function () {
$('div').click(function (e) {
e.stopPropagation();
alert(giveId(this));
});
});
Updated Demo in action

Try this: JSFiddle (The easiest solution!)
$(document).ready(function(){
var currDiv = $("#comment-4"); // Try with different valies: "#comment-x"
currDivId = currDiv.prop('id');
lastDivId = currDiv.parent('div').find('.comment').last().prop('id');
if(currDivId == lastDivId){
var nextComment = currDiv.parent('div').next('div').find('.comment').prop('id');
}else{
var nextComment = currDiv.parent('div').find('.comment').next().prop('id');
}
alert(nextComment);
});

Related

How to get index, position number of element with certain class with jQuery

I have this markup
<div class="parent">
<div class="one"></div>
<div class="two"></div>
<div class="one"></div>
<div class="two"></div>
</div>
My question is: how to get "index" number of element with class two. I'm not asking of regular index number of element in parent div. I need to know that when i'm clicking at first element with class one that next two element have 0 index or it's first element in this list with class two, and so on.
I've tried with index() method and eq() and always i have the real index number of this element in parent div. I hope this is clear, thx for help.
You need to find the elements index in collection of element with sameclass:
$('.parent > div').click(function(){
var index;
if($(this).is('.one'))
index = $('.parent > .one').index(this);
else
index = $('.parent > .two').index(this);
});
This should be the faster way to get the index you are looking for.
Instead of retrieving all matches, it just counts the number of elements of the same class among previous leafs in your DOM.
Also, it allows having multiple <div class="parent"> and still work
$('.parent div').click(function() {
// Retrieve clicked element class (one, two)
var elClass = $(this).attr('class');
// Retrieve all previous elements that have the same class
// and count them
var prevElmts = $(this).prevAll('.' + elClass),
numPrevElements = prevElmts.length;
console.log(numPrevElements);
})
Using jquery you can find index of element which have same class name or tag name
$(".class_name").on("event_name", function() {
var index=($(this).index());
console.log('index : ',index);
});
This may work for you.
var p = $('.parent'),
current = p.filter('.two'),
index = p.index(current);

Jquery previous object selector

I have an issue about prev object on jquery it doesnt give me position ...
I have divs with ".post-image"
$(".post-image").each(function(){
var div = $(this);
var index = div.index();
var odd = index % 2;
if(odd == 1){
var sibling = div.next();
sibling.css({
margin:"15px",
marginTop:"-165px"
})
var bElement= div.prev(".post-image");
console.log(bElement)
})
HTML:
<div class="post">
<div class="post-header"></div>
<div class="post-content"></div>
</div>
<div class="post-image">
<div class="post-header"></div>
<div class="post-content"></div>
</div>
I cant select prev as an object
As for the jQuery docs:
.prev( [selector ] ) Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
Reference
Your <div class="post-image"> element has no immediately preceding element with the same class. The element preceding it is <div class="post">
[EDIT]
You can go this way:
// declare bElement variable:
var bElement;
$(".post-image").each(function(){
var div = $(this);
var index = div.index();
var odd = index % 2;
if(odd == 1){
var sibling = div.next();
sibling.css({
margin:"15px",
marginTop:"-165px"
});
// make sure that previous element with class '.post-image' exists :
if(bElement !== undefined){
var prevElemPosition = bElement.position().top;
// do something ...
}
}
// set latest .post-image element (so that it will be the previous on next iteration):
bElement = div;
});

jQuery - Trouble with children

I have a container with several divs inside of it. Only one of the divs should should at a time. The container is essentially just a jQuery slider of divs. It should show and hide the next/prev div depending on which button you click, but it returns an error on the following line:
children[current--].show();
I'm not sure as to why this is happening. I am calling children (an array) then trying to access the index with an int--, then showing it, but it never shows.
Here is a jsFiddle: http://jsfiddle.net/n6fW7/1/
HTML:
<div id="container">
<div id="content">
<div id="prev" class="arrow">></div>
<div id="next" class="arrow"><</div>
</div>
</div>
jQuery:
$(function(){
$('#content').append('<div class="box"><p class="title">1</p><p class="text">abc</p></div><div class="box"><p class="title">2</p><p class="text">efg</p></div>');
var children = $('#content').find('.box');
var count = children.length;
var current = 1;
$('.box').not(children[0]).hide();
$('.arrow').click(function(){
var where = $(this).attr('id');
if(where == 'next'){
if(current != count){
current++;
}
}
else{
// previous
if(current > 2){
current--;
}
}
$('.box').hide();
children[current--].show();
});
});
Using the indexer in a jQuery object returns the raw DOM element, which does not contain the show() function. You can use the eq() function instead of the indexer, which returns a jQuery object wrapping the DOM element:
children.eq(current--).show();

finding index of parent of a certain class

I have the following HTML:
<div class="Wrapper">
<div class="SomeOtherClass"></div>
<div class="SomeOtherClass"></div>
<div class="MyClass">
<div class="SomeElement" id="test"></div>
<div class="SomeElement"></div>
</div>
<div class="MyClass">
<div class="SomeElement" id="test2"></div>
<div class="SomeElement"></div>
</div>
</div>
And I have the following javascript:
$('.Wrapper').find('.SomeElement').each(function () {
if (SomeCondition) {
var TheElement = $(this);
var TheIndexOfParentClass = TheElement... //HERE
return;
}
});
As you can see, I loop through all the SomeElements and I pick one. Now I want to know the index of the parent's class (here "MyClass"). For instance, if I pick out "test" then the TheIndexOfParentClass should be 0 and if I pick out test2 then TheIndexOfParentClass should be 1. Note that the number of elements of SomeOtherClass can vary; I don't want the actual index of the parent, I want the index of the parent's class relative to all children of the Wrapper element. How do I do this?
Thanks.
I think you want this :
$('.Wrapper').find('.MyClass').each(function(TheIndexOfParentClass) {
$('.SomeElement', this).each(function(){
if (SomeCondition) {
var TheElement = $(this);
each pass to the callback the iteration index and so by decomposing the iteration you can ask jQuery to count for you.
If you want to stick with your flow, You could do this also by passing class to index method,
$('.Wrapper').find('.SomeElement').each(function () {
if (SomeCondition) {
var TheElement = $(this);
var TheIndexOfParentClass = TheElement.parent().index('.MyClass'); //HERE
return;
}
});
What we are avoiding here is double each loop.

javascript to change innerHTML

I want to change content of div "act" using nextSibling of another div.
But result is - undefined.
function inner(){
var abc = document.getElementById("start").nextSibling;
document.getElementById("act").innerHTML = abc.innerHTML;
}
<img id="btnRight" src="img/btnRight.png" onclick="inner()">
<div id="act"><img src="img/home01.jpg"></div>
<div id="store">
<div id="start">
<img src="img/img01.jpg">
</div>
<div>
<img src="img/img02.jpg"> //wanted to place into "act"
</div>
<div id="end">
<img src="img/img03.jpg">
</div>
</div>
Use nextElementSibling, nextSibling could be a text node
function inner(){
var abc = document.getElementById("start").nextElementSibling;
document.getElementById("act").innerHTML = abc.innerHTML;
}
FIDDLE
If you target browser doesn't support nextElementSibling you can traverse the siblings and find the first element node.
function nextElementSibling(element) {
while (element.nextSibling){
element = element.nextSibling;
if (element.nodeType == Node.ELEMENT_NODE){
return element;
}
}
return undefined;
}
FIDDLE
You have to make sure to skip over whitespace when traversing nodes.
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function inner(){
var abc = next(document.getElementById("start"));
document.getElementById("act").innerHTML = abc.innerHTML;
}
You can see a working example at http://jsfiddle.net/CkCR3/.
The cause of this behaviour is white space between div with id "start" and the following div. So, nextSibling will be text content. You need to do nextSibling twice:
var abc = document.getElementById("start").nextSibling.nextSibling;
Another option is to remove whitespace characters between two divs.
Please change your line of code as per below;
because every next element is check for exists or not ,then get inner html.
function inner() {
var abc = document.getElementById("start");
do {
abc = abc.nextSibling;
} while (abc && abc.nodeType != 1);
document.getElementById("act").innerHTML = abc.innerHTML;
return false;
}
I've made a jsfiddle to demonstrate an easier way.
You'll notice that the act div is red and that the start div is blue. The innerHTML will change when you click the button. Also, a reason that you might see undefined is because the DOM didn't load and so it doesn't have any idea that the divs exist. Next time you should use window.onload = inner(); to make the function run after the DOM has loaded.
This is the jsfiddle: http://jsfiddle.net/yY9Ag/16/
there are two way
first fix the code
nextSibling.nextSibling.innerHTML
or fix the html : remove all \n char
<img id="btnRight" src="img/btnRight.png" onclick="inner()"><div id="act"><img src="img/home01.jpg"></div><div id="store"><div id="start"><img src="img/img01.jpg"></div><div><img src="img/img02.jpg"> //wanted to place into "act"</div><div id="end"><img src="img/img03.jpg"></div></div>​
because div tag's next sibling is empty textNode (it can't see)

Categories

Resources