find index of div using jquery - javascript

here is my html code:
<div class="more-content">
<input type="text" />
<div class="post">post 1</div>
<div class="post">post 2</div>
<div class="post">post 3</div>
</div>
Here is jquery:
$(".post").click(function () {
var index = $(this).index();
alert(index);
});
i don't want to consider the input text while trying to get index of div inside of main div.Hence clicking on post 3 must show 2 and not 3.How to do that??
here is the jsfidle http://jsfiddle.net/NDySY/16/

You can use index() this way:
$(".post").click(function() {
var index = $(this).index('.post');
alert(index);
});
Fiddle

You can use: $('.post').index(this)
check: http://jsfiddle.net/NDySY/18/

Working Demo http://jsfiddle.net/cse_tushar/NDySY/21/
div.post means only div with class post
$("div.post").click(function() {
var index = $(this).index('div.post');
alert(index);
});

in class post click event fetch index as follow:
var index=$('.post').index(this);

You will have to get the number of post then subtract it by the index. You index function should also have a parameter for the selector where it should be relative to
$(".post").click(function() {
var index = $(this).index('.post');
var comp = $('.post').length - index;
alert(comp);
});
http://jsfiddle.net/NDySY/24/

You can do something like this.
$(".post").click(function() {
var eventCreator=this;
$('.post').each(function(index,value){
var currentDiv=value;
if(eventCreator==currentDiv)
{
alert(index);
//Do what ever you want to do with index
}
});
});
Check the JS Fiddle HERE

Related

Modify the contents of child divs inside another div using JavaScript/JQuery

<div id="abc">
<div id="a_b"> abcd </div>
<div id="c_d"> xyz </div>
</div>
Problem is the divs are dynamically generated and their IDs keep changing every time the page is rendered. On window load, the contents of a_b and c_d has to be passed a function func() and the output should be placed within the same div. How can I grab each child of div abc and modify their contents?
Try to use .text() along with .each() to achieve what you want.
$(window).load(function(){
$("#abc > div").each(function() {
$(this).text(someFunction($(this).text()));
});
});
Or the better code would be using the receiver function of .text(),
$(window).load(function(){
$("#abc > div").text(function(_,v) {
return someFunc(v);
});
});
Given that the #abc div is always available, you can select that and then any direct child div element and loop over them by using text() with a handler function, like this:
$('#abc > div').text(function(i, v) {
return v + ' foobar';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc">
<div id="a_b">abcd</div>
<div id="c_d">xyz</div>
</div>
Alternatively you can create an array of the content of the child divs and pass that to your func():
var textContents = $('#abc > div').map(function() {
return $(this).text();
}).get();
func(textContents);
function func(arrText) {
console.log(arrText); // = [ 'abcd', 'xyz' ]
}

jQuery.each() class example Appending Div Text to Li

$EACH DEMO
anyhow iam getting the text of "div class": and printing in console.,
and iam trying to append the same text in "li > button", which is not happening, not sure where iam going wrong,
html :
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
JS:
//step - 1
$.each($('.productDescription'), function() {
var classTxt = $(this).text();
console.log(classTxt);
});
//outputs: Red Orange Green
//step - 2 now im trying to append the text to li
var liBtn = $(this).find('li').next('button');
console.log("Text of Button - "+ classTxt);
console.log(liBtn)
for (var i = liBtn.length; i >= 0; i++) {
liBtn[i]
};
Appreciate Your Help, Thanks
There are several errors in your code. classTxt is undefined outside of the each handler's context and the second this refers to window object and not to the .productDescription elements.
I'd suggest using the .append() method's callback function:
// cache the collection for better performance
var $p = $('.productDescription');
$('li button').append(function (index) {
return $p.eq(index).text();
});
http://jsfiddle.net/46yo7etz/
You could also use the .text() method:
$('li button').text(function(index, currentTextContent) {
// using indices for selecting
// the corresponding `.productDescription` element
return currentTextContent + $p.eq(index).text();
});
Please note that your fiddle's markup is invalid. li element should be child of an ul/ol element.
$('li > button').text(function() {
return $('.productDescription').eq( $('li > button').index( this ) ).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
$("button").each(function(i){
$(this).text( $(".productDescription").eq(i).text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<ul>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
</ul>
http://jsfiddle.net/simply_simpy/uqmpvb7e/

Show/hide div on click if div class names match

I have two sets of divs — one that is the 'main' div and one that is the 'extra' div. Both of these have classes that are brought in via the CMS.
What's the best way of showing/hiding (preferably slideToggle) each div, on click, that corresponds to the div clicked?
<div class="each-business-content-main" data-id="group-1"></div>
<div class="each-business-content-main" data-id="group-2"></div>
<div class="each-business-content-extra group-1"></div>
<div class="each-business-content-extra group-2"></div>
These 'group-1' or 'group-2' classes aren't known in advance so can't be hard-coded in. Essentially I'm wondering how, if you click on one div it shows another div (as long as they share the same class name).
I've tried this so far:
$('.each-business-content-main').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
jQuery('.each-business-content-extra').slideUp();
jQuery('.each-business-content-extra .' + id).slideDown();
});
But I'm guessing hrefs and id might come in useful? Or some other data-id...
If you assign a data attribute to your divs it makes this pretty easy:
<div class="each-business-content-main group-1" data-group="1">main 1</div>
<div class="each-business-content-main group-2" data-group="2">main 2</div>
<div class="each-business-content-extra group-1" data-group="1">extra 1</div>
<div class="each-business-content-extra group-2" data-group="2">extra 2</div>
$('.each-business-content-main').click(function () {
$('.each-business-content-extra.group-' + $(this).data('group')).slideToggle();
});
jsFiddle example
Have you tried replacing this:
jQuery('.each-business-content .' + id).slideDown();
...with this:
jQuery('.each-business-content #' + id).slideDown();
jQuery selects classnames as .classname and IDs as #id.
Try
$('.each-business-content').click(function () {
var that = $(this);
$('.each-business-content').each(function () {
if ($(this) === that) {
$(this).slideUp();
} else {
$(this).slideDown();
}
});
});
Can you try this code at jsFiddle? Don't need group 1 and group 2, I use index instead of the name of the id. Is that all right for you?
$('.each-business-content-main').on('click', function (e) {
$('.each-business-content-extra').(':eq(' + $(this).index() + ')').slideDown();
$('.each-business-content-extra').not(':eq(' + $(this).index() + ')').slideUp();
});

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

jQuery to loop through elements with the same class

I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.
Does anyone know how I would do this?
Use each: 'i' is the postion in the array, obj is the DOM object that you are iterating (can be accessed through the jQuery wrapper $(this) as well).
$('.testimonial').each(function(i, obj) {
//test
});
Check the api reference for more information.
try this...
$('.testimonial').each(function(){
//if statement here
// use $(this) to reference the current div in the loop
//you can try something like...
if(condition){
}
});
It's pretty simple to do this without jQuery these days.
Without jQuery:
Just select the elements and use the .forEach() method to iterate over them:
const elements = document.querySelectorAll('.testimonial');
Array.from(elements).forEach((element, index) => {
// conditional logic here.. access element
});
In older browsers:
var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(element, index) {
// conditional logic here.. access element
});
Try this example
Html
<div class="testimonial" data-index="1">
Testimonial 1
</div>
<div class="testimonial" data-index="2">
Testimonial 2
</div>
<div class="testimonial" data-index="3">
Testimonial 3
</div>
<div class="testimonial" data-index="4">
Testimonial 4
</div>
<div class="testimonial" data-index="5">
Testimonial 5
</div>
When we want to access those divs which has data-index greater than 2 then we need this jquery.
$('div[class="testimonial"]').each(function(index,item){
if(parseInt($(item).data('index'))>2){
$(item).html('Testimonial '+(index+1)+' by each loop');
}
});
Working example fiddle
you can do it this way
$('.testimonial').each(function(index, obj){
//you can use this to access the current item
});
jQuery's .eq() can help you traverse through elements with an indexed approach.
var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
var element = testimonialElements.eq(i);
//do something with element
}
divs = $('.testimonial')
for(ind in divs){
div = divs[ind];
//do whatever you want
}
I may be missing part of the question, but I believe you can simply do this:
$('.testimonial').each((index, element) => {
if (/* Condition */) {
// Do Something
}
});
This uses jQuery's each method: https://learn.jquery.com/using-jquery-core/iterating/
You can do this concisely using .filter. The following example will hide all .testimonial divs containing the word "something":
$(".testimonial").filter(function() {
return $(this).text().toLowerCase().indexOf("something") !== -1;
}).hide();
With a simple for loop:
var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
// Using $() to re-wrap the element.
$(testimonials[i]).text('a');
}
Without jQuery updated
document.querySelectorAll('.testimonial').forEach(function (element, index) {
element.innerHTML = 'Testimonial ' + (index + 1);
});
<div class="testimonial"></div>
<div class="testimonial"></div>
You could use the jQuery $each method to loop through all the elements with class testimonial.
i => is the index of the element in collection and val gives you the object of that particular element and you can use "val" to further access the properties of your element and check your condition.
$.each($('.testimonal'), function(i, val) {
if(your condition){
//your action
}
});
In JavaScript ES6 .forEach()
over an array-like NodeList collection given by Element.querySelectorAll()
document.querySelectorAll(".testimonial").forEach((el, idx) => {
el.style.color = "red";
console.log(`${idx} Element ${el.tagName} with ID #${el.id} says: ${el.textContent}` );
});
<p class="testimonial" id="1">This is some text</p>
<div class="testimonial" id="2">Lorem ipsum</div>
$('.testimonal').each(function(i,v){
if (condition) {
doSomething();
}
});
More precise:
$.each($('.testimonal'), function(index, value) {
console.log(index + ':' + value);
});

Categories

Resources