Select DIV using its ID + addition - javascript

Using a div as selector is easy:
<div id="test1"></div>
$('#test1').doSomething();
I want to target only another div, containing the same ID + _sub:
<div id="test1"></div>
<div id="test1_sub"></div>
$('#test1').find( /* Same ID + "_sub" */ ).doSomething();
How can I do this? I know I can use .attr('id') to take #test1, but I do not how to extend this with _sub.
JS FIDDLE
Of course it would be easy to target the #test1_sub directly, but image I have 1000 divs counting up test1, test2, test3, etc. and want to use this inside of a function.

You do it like this
$('#test1' + "_sub").fadeOut();
Note the quotation-marks containing "_sub".
EDIT: In your answer, you made up an example where you had 100 divs with ids like test1, test2 and so on. Then you could select all elements with an id beginning with test. Like this:
$('*[id^="test"]').fadeOut();

Here you can use start with selector to work with all ids.
jsFiddle
$(document).ready(function(){
$( "*[id^='test1']" ).fadeOut();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="test1">Test 1</div>
<div id="test1_sub"> Test 1 Sub</div>
<div id="test1_asdf">Test 1 ASDF</div>
<div id="test1_sub342"> Test 1 sub342</div>
<div id="test1_sdfsd">Test 1 sdfsd</div>
<div id="test1_45645"> Test 1 45645</div>

Set a variable and chain: (CORRECTED)
var target = $(whatever test div you targetted).attr('id');
$('#'+target + "_sub").doSomething();
You said you were going to use it in a function, so it would be targettable this way for example. Lets say when you click #test1 a function will run on all subs based on the clicked test:
$('.testBoxes').click(function () {
var target = $(this).attr('id');
$('#'+target + "_sub").doSomething();
});

Related

Loading content in a target div using jquery

So the first part of the code works fine as it should be, the two grid and list view loads in the views-div when clicked, however, I want a default view shown in the views-div using jquery, I tried loading using clone and prependto but it doesn't work. any suggestion on how to do this?
note: the content I'm loading from the backend has tags and ID's so if I use the html markup to show a default content in the views-div the content repeats. So I'm hoping if use jquery to load content, the repeating will not occur.
here's a demo http://jsfiddle.net/soulsurfer/eta0uyye/
$(document).ready(function() {
$('.iw-grid-select, .iw-list-select').on('click', function() {
var aID = $(this).attr('href');
var elem = $('' + aID).html();
$('#iw-grid-view').fadeOut("slow", 1000);
$('#iw-listview').fadeOut("slow", 1000);
$('#iw-views-div').html(elem);
});
$( "#iw-grid-view" ).contents().find( ".iw-grid-list-col" ).clone().prependTo("#iw-views-div");
});
The simplest solution could be is to trigger a click event
$(document).ready(function() {
$('.iw-grid-select, .iw-list-select').on('click.view', function() {
var aID = $(this).attr('href');
var elem = $('' + aID).html();
$('#iw-grid-view').fadeOut("slow", 1000);
$('#iw-listview').fadeOut("slow", 1000);
$('#iw-views-div').html(elem);
}).first().trigger('click.view');
});
.iw-listview,
.iw-grid-view {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="iw-filter-col ">
grid view link
list view link
</div>
<div class="row iw-listing-view-row">
<div class="iw-grid-view" id="iw-grid-view">Grid view content</div>
<div id="iw-listview" class="iw-listview">list view content</div>
<div class="iw-views-div" id="iw-views-div">Content loading column</div>
<div id="loading"></div>
</div>
I know that this has been resolved, but just in case anyone was wondering where OP went wrong, I have a theory.
This:
$( "#iw-grid-view" ).contents().find( ".iw-grid-list-col" ).clone().prependTo("#iw-views-div");
Should be changed to this:
$( "#iw-grid-view" ).find( ".iw-grid-list-col" ).clone().prependTo("#iw-views-div");
If the .iw-grid-list-col element was an immediate child of #iw-grid-view, then find() wouldn't have found it when called on the return value of contents(). This is because find() searches through descendants of elements. The return value of contents(), in this case, would have included the .iw-grid-list-col element and find() would not have found it since it was a member of the array that find() was called on, rather than a descendant of a member of the array.
Removing contents() from that chain of function calls allows find() to search all of the descendants of #iw-grid-view instead of just the descendants of its immediate children.

Find followers of an element in a certain scope, which aren't siblings

I am trying to select all following elements of an element I choose. They don't necessarily have to be direct siblings of my chosen Element, so .nextAll() won't work.
Here's an example:
<div class="scope">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 4 </div>
</div>
NOT THIS
My element is a[href="2"], so I want to select a[href="3"] and a[href="4"], but not a[href="x"] because it's not in my scope.
I found this, but it only fetches one follower, but I need all of them.
I just wrote this, which works great, but it seems odd to me and I am sure that there have to be better solutions than this one:
var $two = $('a[href="2"]');
var selection = [];
var comes_after_2 = false;
$two.closest('.scope').find('a').each(function(){
console.log(this, $two.get(0));
if(comes_after_2){
selection.push(this);
}
if(this == $two.get(0)){
comes_after_2 = true;
}
});
$(selection).css('background', 'red');
Here is a Fiddle to test it: http://jsfiddle.net/mnff40fy/1/
Please feel free to modify it, if there's a better solution. Thank you!
var $all_a = $two.closest('.scope').find('a');
// Get the position of the selected element within the set
var a_index = $all_a.index($two);
// Select all the remaining elements in the set
var $followers = $all_a.slice(a_index+1);
$followers.css('background', 'red');
DEMO
How about this?
JSFiddle
I changed the markup a little to have the href='#' so you could click each one and see how the other elements respond.
$('a').click(function(){
$('a').css('background', 'none');
var scopeDiv = $(this).closest('div.scope');
var thisIndex = $(scopeDiv).find('a').index(this);
$(scopeDiv).find('a').not(this).each(function(index){
if(index >= thisIndex)
$(this).css('background', 'red');
});
});
As an alternative, you can use .nextAll() if you modify it a bit.
In your html code, you placed the a elements as children of the div tags. In order to incorporate .nextAll() you should select for the wrapper div elements and then call .nextAll() and then select for the children a elements.
Here is what I mean.
html
<div class="scope">
<div>
1
</div>
<!-- Start Here -->
<div class="start">
2
</div>
<div>
3
</div>
<div>
4
</div>
</div>
NOT THIS
js
$( '.start' ).nextAll().children( 'a' ).css( 'background-color', 'red' );
Explanation:
I select the wrapper div with $( '.start' )
I then select all of its subsequent siblings with .nextAll()
Of those siblings, I select their children that match 'a'
I apply the css
And here is the Fiddle

How to find the last two elements with the same class in a div and assign them a class?

<div id="main-container">
<div class="box">apple</div>
<div class="box">bus</div>
<div class="box">cattle</div>
<div class="box">dog</div>
<div class="box">eggplant</div>
<div class="box">fox</div>
<div class="box">goat</div>
</div>
How do I find the last two ".box" within "#main-container" and then assign them with a specific class?
Use the slice method to get the last 2 child elements & then add a specific class you wanted.
$('#main-container .box').slice(-2).addClass('someclass')
You can select the last 2 boxes with the css selector nth-last-child:
.box:nth-last-child(-n+2) {}
http://jsfiddle.net/ekDbA/
browser support IE9+ https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child?redirectlocale=en-US&redirectslug=CSS%2F%3Anth-last-child
For your specific question...
var main = document.getElementById('main-container');
var boxes = main.getElementsByClassName('box');
boxes[boxes.length - 2].className += ' a-class'; // 2nd to last
boxes[boxes.length - 1].className += ' a-class'; // last
As PitaJ said, though, there may be a better way to achieve your actual goal, if you would convey it.

selecting div that contains div with a certain value

I have several outer divs, all of them contain 3 inner divs class1 class2 class3. I want to select the outer div based on the value attribute of its inner div that has class1. For example, I want to select the first div because its class1 div has value x. How do I do this with jquery?
<div> <-----this is the div I want to select
<div class="class1" value="x"></div>
<div class="class2" value="y"></div>
<div class="class3" value="z"></div>
</div>
<div>
<div class="class1" value="a"></div>
<div class="class2" value="b"></div>
<div class="class3" value="c"></div>
</div>
My first thought was:
$('.class1[value="x"]').parent();
But I wasn't sure of the syntax (edit: it works). This, however, could work as well:
$('.class1').filter(function() {
return $(this).attr("value") == "x";
}).parent();
Note however, these will only return the first parent (in the case of multiple child divs having a matching "value" attribute). If you want to do something with multiple parent matches, you could iterate through the result with $.each and look at them individually:
$('.class1[value="x"]').each(function() {
var parent = $(this).parent();
});
$('div').has('div[value=x]');
demo
$('div:has([value=x])').closest('div');
demo 2
$('div[value=x]').parents('div');
demo 3
$('div>div[value=x]').parent('div');
demo 4
$.fn.getChildVal = function(val){
$('[value='+val+']').parent().css({background:'red'});
};
$('div').getChildVal('x');
plugin :)
From the docs:
http://api.jquery.com/closest
http://api.jquery.com/has
Another way is to use :has selector
var elem = $('div:has(.class1[value="x"])');
You can do it so.
$(document).ready(function () {
$("div.class1 [value='x']").parent('div');
});

Best Practice for Hiding/Showing Multiple Divs with jQuery

Suppose I have some divs which I want to allow users to switch between. I would write functions like this:
show_A = function () {$('.a').show(); $('.b').hide(); $('.c').hide();}
show_B = function () {$('.a').hide(); $('.b').show(); $('.c').hide();}
show_C = function () {$('.a').hide(); $('.b').hide(); $('.c').show();}
Then attach these functions to links or whatever. What's the best practice for abstracting out this sort of behavior? The total amount of code grows at N^2 with the number of divs, which is no good.
Give all those divs that you want to hide a common class name and then show one of those. like:
html:
<div class="a toggle">a div</div>
<div class="b toggle">b div</div>
<div class="c toggle">c div</div>
Now the js:
show_A = function () {$('.toggle').hide(); $('.a').show();}
show_B = function () {$('.toggle').hide(); $('.b').show();}
show_C = function () {$('.toggle').hide(); $('.c').show();}
The way I've handled this is before was just to hide them all then show the one (or ones) that you want visible.
Something like...
var showSingleDiv = function(klass) {
$('.container > div').hide();
$(klass).show();
};
Granted you don't want to hide every div so you'll need to setup whatever .container is with your own markup.
For each click, you could hide all the divs and then show only the one you need.
You could use a class to tag the divs involved...
<div id="a" class="collapse">...</div>
<div id="b" class="collapse">...</div>
<div id="c" class="collapse">...</div>
And use:
$(".collapse").hide();
You can do something like, by adding a common class to all those elements:
<div class="toggle">a</div>
<div class="toggle">b</div>
<div class="toggle">c</div>
$('.toggle').click(function(){
$('.toggle:visible').hide(); //Hide all visible 'toggle' div's
$(this).show(); //Show the clicked div
});
You can use the :not() selector.
show_A = function () {$('.a').show(); $('div:not(.a)').hide();}
Maybe I'm not understanding the question, but it seems like what he's wanting is something along these lines:
$('div').each().click( function(){
var cls = $(this).attr('class');
if( $("div[class*='"+cls+"']").is(':visible')){ $("div[class*='"+cls+"']").hide();}//
else{ $("div[class*='"+cls+"']").show(); }
}
);
//Disclaimer - I did not check to see if the concatenated selector works, but adapted it from a reputable blog.

Categories