jQuery indexOf function? - javascript

I'm trying to get a location of an element in a jQuery set.
Here's what I tried so far.
I want to be able to do something like this:
$('ul').find('a').indexOf('.active');
And get the location of the .active in the set of a's.
Is there something like an indexOf() function for jQuery? The index() method doesn't work

if you pass a jQuery set ($searchFor) as an argument to the index method of another jQuery set ($searchIn) i.e.
$searchIn.index($searchFor)
it will return the index of $searchFor in the set $searchIn
In your example:
$('ul a').index($('ul a.active'));
​

You just need to give the index function a jQuery object:
var elements = $('ul a');
var index = elements.index(elements.filter('.active')); // 2
alert(index);
Live DEMO
​
There is no such function out of the box, it can be done easily like this:
var index = -1;
$('ul a').each(function(i){
if ($(this).hasClass('active')){
index = i;
return false;
}
});
alert(index);
Live DEMO

Your logic is sound, you're just grabbing the wrong element: http://jsfiddle.net/xz9dW/19/
var index = $('ul a.active').closest('li').index();
The a link has no index() value since it has no siblings; you have to grab the li

You can do this by just asking for it in the selector:
$('ul a.active')
What do you mean by getting the location however? Do you mean position? or URL?
If you would like to know which one you click on lets say.. You would use $(this) inside your event function. Here is an example which returns the current position of the element you click on, if there are multiple with the .active class:
To get the position:
$('ul a.active').click(function(){
alert( $(this).position() );
})
To get the URL location:
$('ul a.active').click(function(){
alert( $(this).attr('href') );
})

Related

A one-liner for finding the index of an element that has certain class within a jQuery set of elements?

I've got an arbitrary structure like this:
<h2>Foo</h2>
<p>Foo foo</p>
<p>Foofoo</p>
<h2>Bar</h2>
<h2 class=highlighted>Baz</h2>
<p>Baz</p>
<h2>Quux</h2>
<p>Quux quux</p>
In my JS i already have all h2 elements in a jQuery object:
var $headings = $('h2');
Now i need to find which of those headings has the highlighted class.
So for the above structure the third heading is highlighted, so i expect to receive the answer 2 (JS counts from zero).
I've managed to solve this task with:
function foo($jQueryObject) {
var number;
$jQueryObject.each( function(index, element) {
if ($(element).hasClass('highlighted')) {
number = index;
return false;
}
});
return number;
}
Demo: http://jsbin.com/acaGeJi/1/
But i'm sure there's a more elegant way, something like $headings.index('.highlighted');. Can you please suggest it?
You can use the map method to get the index:
var index = $jQueryObject.map(function(i, e){
return e.hasClass('highlighted') ? i : null;
})[0];
You can also use the index method, but then you have to get the element to look for first, so that means that you look for it twice:
var index = $jQueryObject.index($jQueryObject.filter('.highlighted'));
You can use the $.index function
var search = $( ".highlighted" );
alert( "Index: " + $( "h2" ).index( search ) );
This works for me:
$('.highlighted').index('h2');
jsfiddle demo

finding the index of an element in relation to a specific parent

Looking at the example here - http://jsfiddle.net/uqYeQ/3/
The first row behaves as expected, returning the index of the div within it's parent.
I'd like the 2nd row to behave in the same way, I'd like it to return between 0 and 4 depending on which div has been clicked. I'd like to know the index of the div that has been clicked in relation to it's parent list item.
I cannot change the html at all.
Give this a whirl (fiddle)
$("li > .myclass, li > .container").click(function(e){
$("#result").html($(this).index());
});
​
This worked for me (fiddle)
$('.myclass').click(function(){
var theIndex = $(this).index();
$('#result').html(theIndex);
})
$('.container').click(function(){
var theIndex = $(this).index();
$('#result').html(theIndex);
})
but antisanity's is sexier.
The following is one approach
$('.myclass').click(function() {
var liElem = $(this).parents('li')[0]; // get li element who is a parent of the clicked element
var elems = $(this).parents();
elems.push($(this)); //array contains all parents of the clicked element and the clicked element
$(elems).each(function(key, elem) {
if ($(elem).parent()[0] == $(liElem)[0]) {
$('#result').html($(elem).index());
}
});
})
jsFiddle

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

Renumbering numerically ordered div ID's when adding one in the middle with Javascript

I'm developing an application with javascript. What I need is to have divs with id's (1,2,3...) and be able to insert a div between, for example, 2 and 3, with jquery, and then have that be the new three, and three becomes four, four becomes five, etc. I've got the div insertion working, I just need to know how to reorder the divs. Any ideas?
After you inserted the new div, you can do this:
var i = 1;
$('div').each(function() {
$(this).attr('id', i++);
});
Replace $('div') by your own selector.
Remember also that, depending on which version of HTML you use, id's can't start with a number.
You can't start IDs with a numeric value, but regardless of that you'd do something like
// set a data value in the div you have just inserted into the dom and set a variable theID to the current ID you have just inserted.
$(this).data('inserted', true);
var theID = $(this).attr('id'); // this will be 3.
// now to update the other divs.
$('div').each(function() {
if($(this).attr('id') >= theID && !$(this).data('inserted')){
$(this).attr('id', $(this).attr('id') + 1);
}
});
// now set the data inserted to false for future updates
$('div#3').data('inserted', false);
$(function() {
reorder();
$('#click').click(function() {
$('<h2>hello world blah!</h2>').insertAfter('.content h2:eq(1)');
reorder();
});
});
function reorder() {
$('.content h2').each(function(i) {
$(this).attr('id', 'order_'+(i+1));
// alert( parseInt(this.id.split('_')[1]) ); // this is the id #
});
};
I'm pretty sure that you get things back in DOM order from jQuery selectors, so couldn't you just find the parent element, select the child <div> elements, and then .each() through the list?

jQuery: Pass variable to :eq() does not work

I have been trying to find out why the following lines of code do not work:
$('#add-cloud > select').change(function() {
var selected = parseInt($('#add-cloud select option:selected').val());
$("#cloud-calculator table tr:eq(selected)").css("color", "red");
});
If I change :eq(selected) to :eq(4) for example - works fine. How do you pass variable as an argument to :eq() ?
You have to concatenate your variable with your selector:
$("tr:eq("+selected+")");
The way you're doing it, you're embedding the actual string "selected" in the selector. You need to construct a string using your selected variable as a part of it:
$("#cloud-calculator table tr:eq(" + selected + ")").css("color", "red");
Also, you can simply use the 'this' object to get the seleted value.
$('#add-cloud > select').change(function()
{
var rowSelector = '#cloud-calculator table tr:eq(' + parseInt(this.val()) + ')';
$(rowSelector).css("color", "red");
}
Yes we can pass variable to eq() function. But you need to disable Firebug. Otherwise it wont work.
Please check this example.
var index = 3
$('#sidebar_menu li:eq('+index+')').css({"color":"#050959"});

Categories

Resources