Wrap pairs of elements? - javascript

If you have the following code:
<div class="parent">
<div class="1a"></div>
<div class="1b"></div>
<div class="2a"></div>
<div class="2b"></div>
<div class="3a"></div>
<div class="3b"></div>
</div>
Is there an efficient/easy way to wrap a new div around each a + b so it finishes looking like this:
<div class="parent">
<div class="new-1">
<div class="1a"></div>
<div class="1b"></div>
</div>
<div class="new-2">
<div class="2a"></div>
<div class="2b"></div>
</div>
<div class="new-3">
<div class="3a"></div>
<div class="3b"></div>
</div>
</div>
For example can I say something like:
wrap every two divs inside .parent with <div class="new-(incremental variable)"></div> (the new wrapping divs need to have a unique class)

Like this?
$('.parent > div:odd').each(function(i){
$(this)
.prev()
.addBack()
.wrapAll($('<div/>',{'class': 'new-' + (i+1)}));
});
Demo
Get the odd ones selected i.e 1, 3, 5 etc based on index(0 based); Iterate the odd ones get the prev element relative to the odd(which needs to be paired), use andSelf addBack to select that too and then use wrapAll on the pair.
if you want to ignore first x of them then do this:
$('.parent > div:gt(' + (x-1) + '):odd').each(function(i){
$(this)
.prev()
.addBack()
.wrapAll($('<div/>',{'class': 'new-' + (i+1)}));
})
Demo

You can literally use jQueries Wrap function. Take a look here!
http://api.jquery.com/wrap/

I'm not sure what you wish to achieve with the new wrapper divs but nth-child in CSS might be useful. Try something like this:
div.parent div {width:50%;}
div.parent div:nth-child(odd) {clear:both; float:left;}
div.parent div:nth-child(even) {float:right;}
...which will give you pairs of divs side by side.

Related

Get Div by Id and Id of Div contains multiple values jquery

I have a Div element on my HTML page, and that DIV is coming from an ASP.NET application, so the DIV ID is changing all the time but few words remain the same in that id.
For example:
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGrid"> </div>
The only things which remains same all the time in above example are "_UWT" & "_NewGrid".
I know how to get the by Exact ID or atleast by using the 1 word in this: $( "div[id$='_UWT']" )
But I need to get this Div element by using the multiple parameters:
I need to check the "_UWT" and "_NewGrid" also.
If both words exist in the Div id, then return me the element only.
I need to get this DIV by JQuery.
I know I can set the ClientID to Static from ASP.NET, but that is not doable in my case.
Thanks.
To achieve this you can combine the 'attribute contains' selector (to find the _UWT) and the 'attribute ends with' selector (to find the _WebGrid), like this:
$('div[id*="UWT"][id$="_NewGrid"]').addClass('foo');
.foo {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00_ctl01_ctl00_ctl04_NewGrid">Not this one</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04">Not this one</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04_NewGrid">This one</div>
One way could be:
$('div').each(function() {
if($(this).attr('id').includes('_NewGrid') && $(this).attr('id').includes('_UWT')) {
console.log($('div').attr('id'));
$(this).css('color','red') // do whatever you want with div
}
})
Demo:
$('div').each(function() {
if($(this).attr('id').includes('_NewGrid') && $(this).attr('id').includes('_UWT')) {
console.log($('div').attr('id'));
$(this).css('color','red')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGrid">11111</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGri">222222222</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__ctl01_ctl00_ctl04
_NewGrid">3333333333333</div>
Try following way:
Add specific class I added here item-collection:
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGrid">Div 1</div>
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04">Div 2</div>
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00_ctl01_ctl00_ctl04
_NewGrid">Div 3</div>
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00_ctl01_ctl00_ctl04
_NewGrid">Div 4</div>
JS is:
var itemslist = [];
$(".item-collection").each(function(){
if($(this).attr("id").indexOf("_UWT") > -1 && $(this).attr("id").indexOf("_NewGrid")){
itemslist.push($(this))
}
})
console.log(itemslist);

Add class with a particular div

I have this div
<div class="newDiv">
It is generating in loop, something like
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
Now I want to add another class "BrightDiv" with the div that generated at odd places like
with first and third div.
what should I do to add Class "BrightDiv" along with "newDiv" with every div at odd place?
Try this : You can use :odd or :even to select odd / even elements, but it is depend on the index position and not natural number count. So In your case, you want first and third position div i.e. with index= 0 and 2 which is even by index position and hence use :even.
$('div.newDiv:even').addClass('BrightDiv');
DEMO
You can use filter to select only the odd indexed divs
$(".newDiv").filter(function() {
return $(this).index() % 2 == 1;
}).addClass("BrightDiv");
this will give you a solution $("div:even").addClass("BrightDiv");
Ways to achieve this:
CSS:
.newDiv:nth-child(odd) { /*CSS*/ }
or
.newDiv:nth-child(2n-1) { /*CSS*/ }
jQuery:
$('.newDiv:odd').addClass('BrightDiv');

jQuery check divs has a class and unwrap if no other class

I have two div's and what I am trying to do is loop through all the divs to check if the div has a class jsn-bootstrap3, I'm also trying to check to see if the div has any other classes, if it doesn't then I'd like to remove the jsn-bootstrap3 div so that the child content is whats left.
<div class="jsn-bootstrap3">
<div class="wrapper">
Div one
</div>
</div>
<div class="jsn-bootstrap3 block">
<div class="wrapper">
Div two
</div>
</div>
$('div').each(function() {
if ($(this).hasClass()) {
console.log($(this));
var class_name = $(this).attr('jsn-bootstrap3');
console.log(class_name);
}
});
jsFiddle
You can try something like
$('div.jsn-bootstrap3').removeClass('jsn-bootstrap3').filter(function () {
return $.trim(this.className.replace('jsn-bootstrap3', '')) == ''
}).contents().unwrap();
Demo: Fiddle
use the class selector to find div's with class jsn-bootstrap3 because we are not goint to do anything with others
use filter() to filter out div's with any other class
use unwrap() with contents() to remove the wrapping div

Jquery: parse div blocks and add id(1,2,3,4,5)

I'm trying to make jquery parse list of div blocks and add id to each div one by one with numbers like 1,2,3,4,5 and so.
For example, here is the list of div blocks:
<div class="my-blocks">
<div class="start"></div>
<div class="start"></div>
<div class="start"></div>
<div class="start"></div>
</div>
There can be any amount of div blocks with class "start". Final result must be like this:
<div class="my-blocks">
<div id="1" class="start"></div>
<div id="2" class="start"></div>
<div id="3" class="start"></div>
<div id="4" class="start"></div>
</div>
How can I do that? I just don't really understand where I can start to reach this functionality.
You can use .each() to iterate over child divs and then use index+1 to set it as id value.try this:
$('.my-blocks div').each(function(){
$(this).attr('id',$(this).index()+1);
});
Working Demo
You can do:
$('.my-blocks .start').each(function(i) {
$(this).attr('id', i+1);
});
Also note that number is not valid id, you can use div-1, div-2... instead.
Fiddle Demo
You need to add an alphabetical prefix for the ids, Since setting an id as a numeric value is not acceptable in standards below html5. so that your code would achieve backward compatibility.
Try to use the receiver function of .attr(),
$('.my-blocks .start').attr('id', function(i,_) {
return 'id-' + (i+1);
});
DEMO
You must take care that id starting with number is not allowed until html 4. So if you not working on html5 then you should add some prefix to id.
try each():
$('div.start').each(function(index, element){
$(this).attr('id',index+1);
});
Here is working demo.
Using jQuery 'id' property, loop through each block:
$(function(){
$.each($('.start'), function(i,e){
e.id = i+1;
});
});
JSFiddle here http://jsfiddle.net/PU2T4/
And one more (DEMO):
$('.start').attr('id', function() { return $(this).index()+1; });

targeting a div in an ocean of nested dynamically added divs

I'm using the liferay framework and I need to add a JavaScript detected inline height to a very very specific div in my page. The problem is I need to target it going through an unknown number of dynamically added divs with dynamically added classes and IDs. To complicate this even further, the divs are randomly siblings or nested in each other.
Here's what it looks like:
<div class="known-class">
<div class="unknown dynamicallygenerated"></div>
<div class="unknown dynamicallygenerated">
<div class="unknown dynamicallygenerated">
<div class="unknown dynamicallygenerated"></div>
<div class="unknown dynamicallygenerated">
<div class="DIV-I-WANT-TO-TARGET">this is the div i need to Target with my css/javascript</div>
</div>
</div>
</div>
obviously I can't target it simply with
function resize() {
var heights = window.innerHeight;
jQuery('.DIV-I-WANT-TO-TARGET').css('height', heights + "px");
}
resize();
Because that class is present elsewhere, I would rather target it with something like.
jQuery('.known-class .DIV-I-WANT-TO-TARGET')
Which obviously doesn't work because there's a ton of other divs in the middle and my div is not a child of ".known-class"
I was asking myself if there was any jQuery that could help. Something like:
Catch any div with .DIV-I-WANT-TO-TARGET class that is "generically" inside another div that has .known-class
Is this possible? thanks a lot for your help!
Something like this would work:
// this will target the known-class and find all children with DIV-I-WANT-TO-TARGET
$('div.known-class').find('div.DIV-I-WANT-TO-TARGET');
// this will target the known-class and find the first DIV-I-WANT-TO-TARGET
$('div.known-class').find('div.DIV-I-WANT-TO-TARGET').first();
$('div.known-class').find('div.DIV-I-WANT-TO-TARGET:first');
$('div.known-class').find('div.DIV-I-WANT-TO-TARGET:eq(0)');
$('div.known-class').find('div.DIV-I-WANT-TO-TARGET').eq(0);
You can try in your css file
.known-class div div div div{}
The last div being the DIV-I-WANT-TO-TARGET
Assuming that you are adding the divs starting from the outer to the inner
Assign an equal name plus a number starting from 1
<div class="known-class">
<div class="unknown dynamicallygenerated" id="dynamicdiv1"></div>
<div class="unknown dynamicallygenerated" id="dynamicdiv2">
<div class="unknown dynamicallygenerated" id="dynamicdiv3">
<div class="unknown dynamicallygenerated" id="dynamicdiv4"></div>
<div class="unknown dynamicallygenerated" id="dynamicdiv5">
<div class="DIV-I-WANT-TO-TARGET" id="dynamicdiv6"></div>
</div>
</div>
</div>
The use jQuery [.each][1] to loop through all the divs on the document
$( document.body ).click(function() {
$( "div" ).each(function( i ) {
if ( this.style.color !== "blue" ) {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
When you reach the last item in numeric order. (you can use any split function) add the attributes to that div
you need to select last div inside the known-class:
$('.known-class').find('div:last').css('background', 'Red')
OR if you want to select all the .known-class :
$('.known-class').each(function() {$(this).find('div:last').css('background', 'Red')});
Actually your selector works just fine:
$('.known-class .DIV-I-WANT-TO-TARGET')
With a space, selectors will find any descendant.
The search is only limited to direct descendants (immediate children) if you use the > operator.
So $('.known-class > .DIV-I-WANT-TO-TARGET') would not find what you wanted.

Categories

Resources