I am not sure if this is possible...
If you have f.ex.
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
<div id="child6"></div>
</div>
How could you, with jquery or javascript (or anything for that matter), just show the first two?
You can use :gt() jQuery selector.
$("#parent>div:gt(1)").hide()
Actually, if you want to show incrementally, it is better to hide everything first and then use :lt() jQuery selector to show.
$("#parent>div").hide();
var n = 2;
$("#parent>div:lt(" + n + ")").show();
el.click(function () {
n += 5;
$("#parent>div:lt(" + n + ")").show();
});
You can do this with CSS:
#parent div:nth-child(n+3) {
display: none;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Anth-child
JsFiddle
Here's a way you could do it in jQuery:
// hide all the children
$("#parent>div").hide();
// unhide the two we care about
$("#child1").show();
$("#child2").show();
If you don't have known IDs for your elements, here's a more general solution:
$("#parent>div~div~div").hide();
You could write jQuery code like so:
var visibleIndexes = [0, 1]
$("#parent").children().each(function(index) {
if(visibleIndexes.indexOf(index) === -1){
$(this).hide();
} else {
$(this).show();
}
});
You can store indexes which you want to show in variable visibleIndexes or any other variable and pass it to this function
A simple iterative approach:
$( document ).ready(function() {
var i = 0;
var somevalue = 3;
$("#parent").children("div").each(
function () {
if(i > somevalue) $(this).hide();
i++;
});
});
Related
//style
.TemplateBox1{display:none;}
//Html
<div class="TemplateBox1" id="9"> 1 </div>
<div class="TemplateBox1" id="10"> 2 </div>
<div class="TemplateBox1" id="11"> 3 </div>
//jQuery
$('div', this).each(function (e) { //Do something });
This is a part from my code, at start the divs display (CSSproperty) is none (not shown) and after the user click on a certain button the property of the div changed to block (shown). I need to select only the divs that their property is display:block using jQuery, I tried :
$('div', this).**css("display")=="block"**.each(function (e) { //Do something }); - didn't work..
What do I need to add to my jQuery...
Try to use :visible selector,
$('div:visible')
It seems that you are using TemplateBox1 class to hide those elements, so you can write in this manner too, that is by using :not() selector
$('div:not(.TemplateBox1)')
Try this : :visible selector for div
$(this).find('div:visible').each(function(){
// do stuff here
});
one way is $('div:visible')
another way is (Demo)
$('.TemplateBox1', this).each(function (e) {
var $css = $(this).css('display');
if($css == 'none'){
$(this).css('display','block')
}
});
Why not use pure JS ?
var list = document.getElementsByTagName("div");
foreach(var i = 0;i < list.length, i++)
{
if(list[i].style.display == "block")
{
// do Something;
}
}
First off I'd like to apologise for asking about something so specific but it's been wracking my brain all day and I'm out of ideas.
I'm using jquery to show and hide elements based on their number suffix ie:
<span></span> will target ->
<div class="content" id="cont-1">This is content</div> and it's working perfectly. I'd like to target another element based on the suffix of another element but I'm failing to. Here's the code:
HTML:
<script src="http://code.jquery.com/jquery.js"></script>
1
2
3
<div class="content" id="cont-1"><p>This is content</p></div>
<div class="content" id="cont-2"><p>This is content</p></div>
<div class="content" id="cont-3">
<div class="child" id="child-11"><p>This is the first child</p></div>
<div class="child" id="child-12"><p>This is the second child</p></div>
</div>
<div class="external" id="external-11"><p>I am the first external</p></div>
<div class="external" id="external-12"><p>I am the second external</p></div>
JAVASCRIPT:
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' ){
$('#cont-'+num).fadeIn();
}else{
$('#cont-'+num).fadeOut();
}
}
CSS:
.content{
background:green;
color:white;
padding:5px;
}
.external{
background:blue;
color:white;
padding:5px;
}
.content, .external, .child{
display:none;
}
.active{
display:block;
}
CodePen: http://codepen.io/anon/pen/uFpzE
What I'm trying to achieve is this:
If you click on #tab-3 the .external div that corresponds with the first child of #cont-3 should show.
I've tried this:
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
var random = $('#cont'+num + '.child:first-child').attr('id').replace(/child-/, '');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none'){
$('#cont-'+num).fadeIn();
$('#external'+random).fadeIn({'duration':600,'queue':false});
}else{
$('#cont-'+num).fadeOut();
}
}
...and it isn't working. Where am I going wrong?
I'm not 100% sure what you're trying to accomplish with the code in the document.ready part, but the showCont function does what you requested.
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num)
{
$('.content').fadeOut(300);
$('.external').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
// get the child element's id
var targetID = $("#cont-"+num).children().first().attr('id');
if(targetID)
{
// construct the id of the external element
$('#external-'+targetID.substring(targetID.indexOf('-')+1))
.fadeIn({'duration':600,'queue':false});
}
}
else
{
$('#cont-'+num).fadeOut();
}
}
DEMO
The variable random is not defined in your JS file, and there are some typos regarding the selector elements (e.g. it should be $('#external-'+random) instead of $('#external'+random)). Base on your code, I came up with the following for your reference:
DEMO
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
var random = $('#cont-'+num + ' div:first-child').attr('id').substring(6);
$('#external-'+random).fadeIn({'duration':600,'queue':false});
}
else
{
$('#cont-'+num).fadeOut();
var random = $('#cont-'+num + ' div:first-child').attr('id').substring(6);
$('#external-'+random).fadeOut({'duration':600,'queue':false});
}
}
I think you've got random in the wrong function. The #cont and #external selectors are also missing a trailing dash:
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
var random = $('#cont-'+num + '.child:first-child').attr('id').replace(/child-/, '');
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none'){
$('#cont-'+num).fadeIn();
$('#external-'+random).fadeIn({'duration':600,'queue':false});
}else{
$('#cont-'+num).fadeOut();
}
}
This should be closer to what you're after (untested though).
Once you've got it working, you could look at simplifying it by using data-id="num" attributes on your HTML elements and accessing the id values with .data('id') in your js, then binding the tab buttons from within your DOM ready fn. It would look closer to this:
$(function() {
$('.tab').click(function (e) {
var num = $(this).data('id'),
$child = $('.child[data-id="' + num + '"]')
;
// ...
})
})
I think this changes to your function showCont(num) would do:
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
var value= $('#cont-'+num+' div' ).first().attr("id").slice(-2);
$('#external-'+value).fadeIn();
}
else
{
$('#cont-'+num).fadeOut();
$('.external').fadeOut();
}
I have the folowing code:
html:
<div class="container">
<div class="selected">A</div>
<div>B</div>
<div>C</div>
<div>D</div>
</div>
<button id="next">next!</button>
jQuery:
$("#next").click(function() {
$(".selected").removeClass("selected").next().addClass("selected");
});
What i want is loop through the divs in the container. I can do this to cycle:
$("#next").click(function() {
if ($(".selected").next().length == 0) {
$(".selected").removeClass("selected").siblings(":nth-child(1)").addClass("selected");
}
else {
$(".selected").removeClass("selected").next().addClass("selected");
}
});
But i think there is a simpler way. How can i make it simpler ? (I don't mind if you don't use the next() function).
jsFiddle: http://jsfiddle.net/S28uC/
I 'd prefer siblings.first() instead of siblings(":nth-child(1)"), but in essence you won't be able to wrap around without using some variant of next().length.
Update: If I were writing this from scratch, this is how I 'd do it:
$("#next").click(function() {
var $selected = $(".selected").removeClass("selected");
var divs = $selected.parent().children();
divs.eq((divs.index($selected) + 1) % divs.length).addClass("selected");
});
This approach is motivated by two factors:
When you want to cycle over a collection indefinitely, modulo comes to mind
Getting rid of the if makes for smarter-looking code
When setting the value of divs I preferred $selected.parent().children() over the equivalent $selected.siblings().add($selected) as a matter of taste -- there are practically endless possibilities.
One simple way is this :
$("#container").find("div:eq(0)").addClass("selected");
how about this.
...
var selected = $(".selected").removeClass("selected");
if (jQuery(selected).next().addClass("selected").length == 0
{jQuery(selected).siblings().first().addClass("selected");};
...
In old good AI manner you try to do the deed (addClass), if it worked (length <> 0) nothing more to do, otherwise you try again on the first of the siblings.
You can try this
var cont = $('.container'),
i = 0;
$("#next").on('click', function() {
cont.children().removeClass('selected');
i += 1;
if ( i === document.querySelectorAll('.container div').length ) { i = 0; }
cont.children().eq(i).addClass('selected');
});
var cont = $('.container'),
i = 0;
$("#next").on('click', function() {
cont.children().removeClass('selected');
// increase index for each click
i += 1;
// reset i if it reached to last index
//(hack to force next to go back to first element when we are at the end)
if ( i === document.querySelectorAll('.container div').length ) {
i = 0;
}
cont.children().eq(i).addClass('selected');
});
.selected {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="selected">A</div>
<div>B</div>
<div>C</div>
<div>D</div>
</div>
<button id="next">next!</button>
simply you will increase i for each click and when it reach the end (divs length ) it will be reset.
How do I remove a DIV with a specific value?
<div value="0" class="task_row"></div>
I want to remove the above div which has value 0.
As Ben Rowe points out in the comments, value is not a valid attribute of the div tag. And both the jQuery solution and the solution that uses getElementsByTagName() has to iterate through a list, which is bad for performance. I think that creating an id attribute instead is a better option:
<div id="task_row_0" class="task_row"></div>
And then you can just do:
var div = document.getElementById("task_row_" + taskId);
div.parentNode.removeChild(div);
this is jquery code )):
$('div').each(function(){
if($(this).attr('value') == '0'){
$(this).remove();
}
});
var divs = document.getElementsByTagName('div');
for(var i = divs.length; i; i -= 1) {
if (divs[i].getAttribute('value') == 0) {
divs[i].parentNode.removeChild(divs[i]);
}
}
Edit: Nevermind - Zhasulan beat me to it. :P
With jQuery -
$('div').each(function(){
if($(this).attr('value') == '0') {
$(this).hide();
}
});
Alternative to jQuery/JavaScript you can achieve it via CSS only -
JSFIDDLE
div[value="0"] {
display: none;
}
Or via jQuery using attribute selector:
JSFIDDLE
$("div[value='0']").hide(); /*.remove() as per your requirement*/
I got a series of divs like this:
<div class="message" style="padding-left: 0px;">...</div>
<div class="message" style="padding-left: 20px;">...</div>
<div class="message" style="padding-left: 20px;">...</div>
<div class="message" style="padding-left: 40px;">...</div>
<div class="message" style="padding-left: 20px;">...</div>
And I would like to make a selector that would get me the divs with padding greater then 20px.
Would it be possible with just using jquery? Or I should modify my html tree and add some attribute that would distinguish those elemenents with high padding value?
You can use a filter with a custom function.
$('div.message').filter(function(){
return parseInt($(this).css('padding-left')) > 20;
});
p.s. I don't sure what .css('padding') > 20 will return, I'm guess I need to test it....
You can use filter for this.
var elems = $('div.message').filter(function (){
return parseInt($(this).css("padding-left"),10) > 20;
});
alert ( elems.length );
or using each you can do something like this
$(function(){
var elems = new Array();
$("div.message").each(function(){
if(parseInt($(this).css("paddingLeft"), 10) > 20 )
{
elems.push($(this));
}
});
alert ( elems.length );
});
You could use $('.message') selector, and then loop through your elements finding the one with .css padding-left set to anything you want.
Second solution, involves usage of custom selectors.
You can modify this code I took from my blog:
$.extend($.expr[':'], {
redOrBlue: function(o) {
return ($(o).css("color") == "red")
|| ($(o).css("color") == "blue");
}
});
Usage:
$('div:redOrBlue')
You could use filter()
var col = $('div').filter(function ()
{
return parseInt($(this).css("padding-left")) > 20;
});
or you could create your own selector:
$.expr[':'].myselector = function(obj, index, meta, stack){
return parseInt($(obj).css("padding-left")) > 20;
};
var col = $("div:myselector");