How to divide result given in html() jquery? - javascript

I'm trying to create a function where I click a button and I get content from a <div>. After, I need to divide the content. I mean, if this div has 10 children, I need to save 5 children in my var code1 and the other 5 in var code2. My problem is I'm not able to use html() function. My code looks like:
$(".pluscontrol").click(function(){
var id = $(this).attr("id");
var items=$(this).closest("table").parent().next().children('#'+id).children().length;
var middle = items / 2;
var code1="";
$(this).closest("table").parent().next().children('#'+id).html(
function(index,currentcontent){
if (index < middle )
code1 = code1 + currentcontent;
});
if ( $(".modal-body .row .sdiv").attr("id") == 1 )
$(".modal-body .row #1.sdiv").html(code1);
if ( $(".modal-body .row .sdiv").attr("id") == 2 )
$(".modal-body .row #2.sdiv").html("...");
});
As you can see, at first, I get the children lenght but I get all items.
I've checked this reference but it not helps too much
the var items is the number of items

Giving an argument to .html() makes it change the HTML of the selected elements. If you want to get the HTML, just call .html() with no argument.
To get the HTML of all the elements in a collection, use .map() to iterate, then combine them with .join().
var allChildren = $(".parent").children();
var middle = Math.floor(allChildren.length/2);
var code1 = allChildren.slice(0, middle).map(function(index, element) {
return element.innerHTML + " " + index;
}).get().join(' ');
var code2 = allChildren.slice(middle).map(function(index, element) {
return element.innerHTML + " " + (index + middle);
}).get().join(' ');
$("#out1").html(code1);
$("#out2").html(code2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<div class="child">Test1</div>
<div class="child">Test2</div>
<div class="child">Test3</div>
<div class="child">Test4</div>
<div class="child">Test5</div>
<div class="child">Test6</div>
<div class="child">Test7</div>
<div class="child">Test8</div>
<div class="child">Test9</div>
<div class="child">Test10</div>
</div>
First group:
<div id="out1"></div>
Second group:
<div id="out2"></div>

You can use querySelectorAll which gives u a collection of child element. It also has a length function which you can call. If you want you can chain a foreach method to it. I have broken it down for clarity.
var children = document.querySelectorAll('.parent > div');
var midPoint = Math.round(children.length / 2);
var firstHalf = Array.prototype.slice.call(children,0,midPoint);
var secondHalf = Array.prototype.slice.call(children,midPoint);
firstHalf.forEach(function(elm){
console.log(elm.innerHTML);
});
<div class="parent">
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
</div>

Related

Calculate draggable div index

In my code i try get index of draggable div. Code structure looks like:
<div class="noDragabble dragabbleMother">
<div class="draggableItem"><p>(Place for index number)</p></div>
<div class="draggableItem"><p>(Place for index number)</p></div>
<div class="draggableItem"><p>(Place for index number)</p></div>
</div>
I try something like this in HTML:
<div class="noDragabble dragabbleMother">
<div class="index1" onmouseup="checkIndex(this)"><p>(Place for index number)</p></div>
<div class="index2" onmouseup="checkIndex(this)"><p>(Place for index number)</p></div>
<div class="index3" onmouseup="checkIndex(this)"><p>(Place for index number)</p></div>
</div>
And use script:
function checkIndex(ele) {
var id = ele.id;
setTimeout(function () {
var a = $(".dragabbleMother #" + id).index();
$("#" + id + " p").text(a+1);
}, 1000);
}
The code works because when I change the order of elements the index of the element I dragged changes. However, the index of other elements should also change. Is such a thing possible?

jQuery loop one to one

I have problem with my code.
I have products on my website, each product has his own <a><h1>CODE</h1></a> and I need to take this CODE and paste it before an image. I need to copy element with has class="loop1" and paste it into another element with class="lop1" and then take another element with class="loop2" and paste into element with class="lop2" and so on..
I made class with same numbers for easier copying, but it doesnt work. Can sombody help me?
This is my code:
$('#loop').addClass(function(i) {
return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
return 'loop'+(i+1);
});
function doForm() {
var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
for (var i=0;i<numb.length;i++) {
number = numb[i];
selector = '.loop' + number;
if ($(selector).length != 0) {
val = $(selector).html();
$('lop' + number).html(val);
}
}
}
doForm();
Related html:
<div class="columns">
<div id="loop" class="lop1"></div>
<div class="p-image">
<img src="https://" width="290" height="218">
</div>
<div class="p-info">
<span itemprop="name">PRODUCT</span>
</div>
<div>
So I need to take from "p-info > a" and paste it into div "lop1". Depends on number in class copy and paste HTML into div with same number.
Change $('lop' + radek).html(val); to $('.lop' + number).html(val);
Notice the . at the beginning of lop, it will create a selector to fetch element based on the class.
$('#loop').addClass(function(i) {
return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
return 'loop'+(i+1);
});
function doForm() {
var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
for (var i=0;i<numb.length;i++) {
var number = numb[i];
var selector = '.loop' + number;
if ($(selector).length != 0) {
var val = $(selector).html();
$('.lop' + number).html(val);
}
}
}
doForm();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="columns">
<div id="loop" class="lop1"></div>
<div class="p-image">
<img src="https://" width="290" height="218">
</div>
<div class="p-info">
<span itemprop="name">PRODUCT</span>
</div>
<div>

Including the current node in the find scope

Consider the following snippet as an example:
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>
Given var $set=$('.bar'); I need to select both nodes with foo class. What is the proper way to achieve this. Considering addBack() requires a selector and here we need to use the $set jQuery object and $set.find('.foo') does not select the first node.
use this :
var $set = $(".bar").filters(function () {
var $this = $(this);
if($this.is(".foo") || $this.find(" > .foo").length !== 0){
return true;
} else{
return false;
}
});
Here's one way of going about it:
var set = $('.bar');
var foos = [];
for (var i = 0; i < set.length; i++) {
if ($(set[i]).hasClass('foo')) {
foos.push(set[i]);
}
}
if (set.find('.foo').length !== 0) {
foos.push(set.find('.foo')[0]);
}
console.log(foos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo"></div>
<div class="bar">
<div class="foo"></div>
</div>
The for loop checks all elements picked up with jQuery's $('.bar'), and checks if they also have the foo class. If so, it appends them to the array. The if checks if any of the elements picked up in set have any children that have the foo class, and also adds them.
This creates an array that contains both of the DIVs with the foo class, while excluding the one with just bar.
Hope this helps :)
test this :
var $newSet = $set.filter(".foo").add($set.has(".foo"));
You could use the addBack() function
var $set=$('.bar');
console.log($set.find(".foo").addBack(".foo"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>

How to sort a list of nodes by a given array in an efficient way?

I have this HTML which is a list of elements:
<div class="container">
<div class="apple-0">first-apple</div>
<div class="apple-1">second-apple</div>
<div class="apple-2">third-apple</div>
<div class="apple-3">forth-apple</div>
<div class="apple-4">fifth-apple</div>
</div>
I've gotten an array, for example, which is [3,4,0,2,1] I need to sort the list in to this order.By this I mean that the third element <div class="apple-3">third-apple</div> should be the first. The second element should be the forth-apple.
How can I change it in an efficient way? This is the expected output:
<div class="container">
<div class="apple-3">forth-apple</div>
<div class="apple-4">fifth-apple</div>
<div class="apple-0">first-apple</div>
<div class="apple-2">third-apple</div>
<div class="apple-1">second-apple</div>
</div>
jQuery can be used.
You can do this by looping through the array and appending each div by it's matched index. Try this:
var $divs = $('.container > div').detach();
[3, 4, 0, 2, 1].forEach(function(value) {
$divs.eq(value).appendTo('.container');
});
Working example
Note that if you need to support older browsers (< IE9) then you would need to replace forEach() with a standard for loop.
You can try something like this:
$("#sort").on("click", function() {
var data = [3, 4, 0, 2, 1];
var result = "";
data.forEach(function(item) {
result += $(".container").find(".apple-" + item)[0].outerHTML;
});
$(".container").html(result);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="container">
<div class="apple-0">first-apple</div>
<div class="apple-1">second-apple</div>
<div class="apple-2">third-apple</div>
<div class="apple-3">forth-apple</div>
<div class="apple-4">fifth-apple</div>
</div>
<button id="sort">Sort</button>
Simply iterate the indexes array and keep pushing the child at nth-index
var output = [];
var indexes = [3,4,0,2,1];
indexes.forEach(function(value, index){
output.push($(".container div").eq(indexes[index])[0].outerHTML);
});
console.log(output);
$(".container").html(output.join(""));
Demo
you can try:
UPDATE:
var arr = [3,4,0,2,1];
var nodes = [];
arr.forEach(funtion(value){
var node = $('.container .apple-'+value)[0];
nodes.push(node);
});
$('.container').html(nodes);
demo
Other answers with eq are good, but if you want to sort again with a different array, or the array is unsorted initially, then they would fail. Also you asked for an efficient method, using native loops instead of jquery's each gives performance benefits. So my answer to this is
$(document).ready(function () {
var inputEls = $('#awesomeContainer').find('>').get(),
$output = $('#awesomeOutput'),
order = [3,4,0,2,1],
output = [],
myValue,
newIndex,
i,
length = inputEls.length;
for (i = 0; i < length; i += 1) {
myValue = Number((inputEls[i].className || "").replace("apple-", ""));
if (myValue >= 0) {
myValue = order.indexOf(myValue);
myValue > -1 && (output[myValue] = inputEls[i].outerHTML);
}
}
$output.append(output.join(''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<b>Input: </b>
<div id="awesomeContainer" class="container">
<div class="apple-0">first-apple</div>
<div class="apple-1">second-apple</div>
<div class="apple-2">third-apple</div>
<div class="apple-3">forth-apple</div>
<div class="apple-4">fifth-apple</div>
</div>
<br/>
<b>Sorted: </b>
<div id="awesomeOutput" class="container">
</div>

JavaScript reselect class personally in ListView

I am creating ListView using my template:
HTML:
<div id="ItemTemplate" data-win-control="WinJS.Binding.Template">
<div class="ItemTemplate">
<div class="back"></div>
<div data-win-bind="innerText:Info.shortName" class="shortName"></div>
<div data-win-bind="innerText:value Converters.BeginValue" class="value"></div>
<div data-win-bind="innerText:value Converters.EndValue" class="valueEnd"></div>
<div data-win-bind="innerText:Info.longName"></div>
<img data-win-bind="src:Info.flag" class="flag" />
<div data-win-bind="innerText:change Converters.BeginChange" class="change"></div>
<div data-win-bind="innerText:change Converters.EndValue" class="changeEnd"></div>
<div data-win-bind="innerText:changePercent Converters.BeginChangePercent" class="changePercent"></div>
<div data-win-bind="innerText:changePercent Converters.EndValue" class="changePercentEnd"></div>
</div>
</div>
The issue is when I meet the very long name I need to adjust font-size.
So I do (for each element in list):
JavaScript:
template = document.getElementById('ItemTemplate');
// Adjust font - size
var name = item.data.Info.longName;
// Split by words
var parts = name.split(' ');
// Count words
var count = parts.filter(function(value) {
return value !== undefined;
}).length;
var longNameDiv = $(template).children("div").children("div").eq(4);
if (count > 2) {
// Display very long names correctly
$(longNameDiv).removeClass();
$(longNameDiv).addClass("veryLongName");
}
var rootDiv = document.createElement('div');
template.winControl.render(item.data, rootDiv);
return rootDiv;
CSS:
.veryLongName {
font-size: 10pt;
}
But it doesn't effect selectivly. Moreover seems like it is check conditions for the first time and then just apply the same setting for remaining items. But it needs to change font-size to smaller only in case if the name is too long. So what am I doing wrong? Thanks.
Try by using following code instead, but u must include jquery for it.
jsfiddle : http://jsfiddle.net/vH6G8/
You can do this using jquery's filter
$(".ItemTemplate > div").filter(function(){
return ($(this).text().length > 5);
}).addClass('more_than5');
$(".ItemTemplate > div").filter(function(){
return ($(this).text().length > 10);
}).removeClass('more_than5').addClass('more_than10');
DEMO

Categories