<div id="grape">grape</div>
<div id="apple">apple</div>
<div id="orange">orange</div>
I have an array fruits = ['apple','grape','orange'], how to alter above dom according to the order of my array?
If you have a parent element
<div id="parent">
<div id="grape">grape</div>
<div id="apple">apple</div>
<div id="orange">orange</div>
</div>
then
var fruits = ['apple', 'grape', 'orange'];
jQuery(function () {
var $p = $('#parent');
$p.children().sort(function (a, b) {
return fruits.indexOf(a.id) - fruits.indexOf(b.id)
}).appendTo($p)
})
Demo: Fiddle
You can rebuild the content in order pretty easily:
HTML:
<button id="go">Sort</button>
<div id="fruits">
<div id="grape">grape</div>
<div id="apple">apple</div>
<div id="orange">orange</div>
</div>
Code:
var fruits = ['apple','grape','orange'];
$("#go").click(function() {
var container = $("#fruits");
container.empty();
fruits.forEach(function(item) {
container.append('<div id="' + item + '">' + item + '</div>');
});
});
Working demo: http://jsfiddle.net/jfriend00/muz9tzb6/
Or, you can use the fact that the array contains ID values to rearrange the existing elements like this:
var fruits = ['apple','grape','orange'];
$("#go").click(function() {
var parent = $("#fruits");
fruits.forEach(function(item) {
$("#" + item).appendTo(parent);
});
});
Working demo: http://jsfiddle.net/jfriend00/39kge2rw/
Related
Basically what I need to do is wrap this code output
<a id="show_selected">Click to Show</a>
<div id="selected"></div>
<script type="text/javascript">
function showSelect(){
$("#show_selected").bind("click", function (e) {
e.preventDefault();
$('#selected').text($("#fvip").mapster("get"));
});
}
showSelect();
</script>
which is right now is just plain
<div id="selected">001,002,003,004</div>
to become
<div="selected">
<div class="something">001</div>
<div class="something">002</div>
<div class="something">003</div>
<div class="something">004</div>
</div>
how can I do that? Is that possible? Many thanks
EDIT with brk 's help below:
I try incorporate it in my code like this:
function showSelect(){
$("#show_selected").bind("click", function (e) {
e.preventDefault();
$('#selected').text($("#fvip").mapster("get"));
let wrapContainer = ""
let stringArray = $("#selected").text().trim().split(' ');
$("#selected").empty()
stringArray.forEach(function(item, index) {
let wrapContainer = $('<div class="test">' + item + '</div>');
$("#selected").append(wrapContainer)
});
});
}
showSelect();
but what I'm getting is:
<div id="selected">
<div class="test">001,002,003,004</div>
</div>
where am I doing wrong?
You can get the text and split it. Then loop over that and put that inside a div . Then append the div to the parent element
let wrapContainer = ""
let stringArray = $("#original").text().trim().split(' ');
$("#original").empty()
stringArray.forEach(function(item, index) {
let wrapContainer = $('<div class="test">' + item + '</div>');
$("#original").append(wrapContainer)
});
.test {
color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="original">001 002 003 004</div>
So... I have four divs on a page. All four of them belong to the class foobar. What I wanna do here is give each of them a value from a certain Array in JavaScript. Do note I am using jQuery 3.2.1.
My JavaScript:
var $elements = jQuery.makeArray($(".foobar"));
[1,2,3,4].forEach(function (x) {
$elements.forEach(function (y) {
y.text(x.toString());
});
});
My HTML:
<div class="foobar"></div>
<div class="foobar"></div>
<div class="foobar"></div>
<div class="foobar"></div>
And as always, it does not work. Basically what I wanna do here is give each Number in that Array as the text() for each div.
You are setting the same text to every element inside inner loop. Try this
var $elements = $(".foobar");
[1,2,3,4].forEach(function (x, i) {
$($elements[i]).text(x)
});
Or use .text(func)
var texts = [1,2,3,4];
var $elements = $(".foobar").text(function(i) {
return texts[i];
})
Check this fiddle. https://jsfiddle.net/bj3s92gr/
Bassicaly you have to bucle the divs with class foobar, and assing the position of the array in the html.
var $elements = $(".foobar");
$arr = [1,2,3,4];
$elements.each(function(e){
$(this).html($arr[e]);
});
Create an array of numbers, traverse thru all the .foobar elements, and assign a value from the array.
var $elements = jQuery.makeArray($(".foobar"));
var numbers = [1, 2, 3, 4];
var count = 0;
$(".foobar").each(function() {
$(this).text(numbers[count]);
count++;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My HTML:
<div class="foobar"></div>
<div class="foobar"></div>
<div class="foobar"></div>
<div class="foobar"></div>
Is there any way to check if two divs are having same ids?
I have created divs dynamically and I am finding it difficult to remove the div having a duplicate id, can anyone help here?
I do not know what you are trying to achieve here , but generally you should not have two elements with the same id . But if you have some reason to do this maybe you are building a validator or someting like this you can do the following to count the number of elements
var count = document.querySelectorAll('#test').length;
console.log(count);
then you can loop through them and remove them using
document.querySelectorAll('#test')[1].remove();
Try it with:
$('[id]').each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
You have to loop all the elements as helpers like getElementById() won't work well when their aren't unique.
Example, no need for jQuery. Alerts the duplicate ID.
var idMap = {};
var all = document.getElementsByTagName("*");
for (var i=0; i < all.length; i++) {
// Do something with the element here
var elem = all[i];
if(elem.id != ""){ //skip without id
if(idMap[elem.id]){
alert("'" + elem.id + "' is not unique")
}
idMap[elem.id] = true;
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>
<div id="id4"></div>
<div id="id5"></div>
<div id="id1"></div>
</body>
</html>
var idList = [];
$('*[id]').each(function(){
var id = $(this).attr('id');
if($.inArray(id, idList)){
alert('the id ' + id + ' is already set!');
} else {
idList.push(id);
}
});
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if (ids.length>1 && ids[0]==this){
$("#"+this.id).remove();
}
});
above function use jquery to create array of all IDs with in the document and remove duplicated id
Something like this should do what you want
$('[id]').each(function (i) {
$('[id="' + this.id + '"]').slice(1).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "1">
ola
</div>
<div id = "2">
ole
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
Example based on the link: jQuery: Finding duplicate ID's and removing all but the first
Can you not just control + F and search for the id's? Also if you are using an editor like atom, you can delete every other duplicate in one go after the search.
I'm creating a form which allows the users to add additional content on the fly. The structure of the form is such that there are three dimensions to the form data, i.e., like a movie can play at different theatres and each theatre can have different showing times. The form, therefore has grandparent, parent and child divs, and the parent & child divs can be added to on the press of a button.
Here's a slimed-down version of the code for clarity
<div id="grandparent">
<div id="parent">
Parent 1
<div id="child">
Child 1
</div>
</div>
<button id="addChild">Add Child</button>
</div>
<button id="addParent">Add Parent</button>
<script>
$(function() {
var grandparent_div = $('#grandparent');
var parent_div = $('#parent');
var child_div = $('#child');
var p = $('#grandparent div#parent').size() + 1;
var c = $('#parent div#child').size() + 1;
$('#addChild').on('click', function() {
$('<div id="child">Child '+c+'</div>').appendTo(parent_div);
});
$('#addParent').on('click', function() {
$('<div id="parent">Parent '+p+'<div id="child">Child 1</div><button id="addChild">Add Child</button></div>').appendTo(grandparent_div);
});
});
</script>
JSFiddle here: http://jsfiddle.net/u2vUT/
I can create parent nodes fine, and I can even create child nodes of parents on the first level - the problem comes when trying to add children of dynamically-added parents. It's probably because the 'addChild' button is no longer unique, so $('#addChild').on('click') can't reference it. So, is there a way to make this work (preferably elegant!)?
You should not use ids, use class
<div id="grandparent">
<div class="parent">Parent 1
<div class="child">Child 1</div>
</div>
<button class="addChild">Add Child</button>
</div>
<button id="addParent">Add Parent</button>
then
$(function () {
var grandparent_div = $('#grandparent');
var parent_div = $('.parent');
var child_div = $('.child');
var p = grandparent_div.find('.parent').size() + 1;
grandparent_div.on('click', '.addChild', function () {
$('<div id="child">Child ' + ($(this).siblings().length + 1) + '</div>').insertBefore(this);
});
$('#addParent').on('click', function () {
$('<div class="parent">Parent ' + p + '<div class="child">Child 1</div><button class="addChild">Add Child</button></div>').appendTo(grandparent_div);
});
});
Demo: Fiddle
I am having a bunch of div tags in my html page. Now I need to write a jQuery to calculate the grid's value. In the below example I will be using grid0 as the base id and I want the count in that series which is 1 here.
<div id="grid00">0</div>
<div id="grid01">0</div>
<div id="grid02">0</div>
<div id="grid03">1</div>
<div id="grid04">0</div>
<div id="grid05">0</div>
In another example given below I will be using id's starting with grid1 and the total value is 6. Please guide me!
<div id="grid10">5</div>
<div id="grid11">0</div>
<div id="grid12">0</div>
<div id="grid13">1</div>
<div id="grid14">0</div>
<div id="grid15">0</div>
I tried this jQuery("div[id^='grid0']"). But this is giving me all the elements. But I need the count using the value inside them.
Thanks!
Start by selecting the divs with the starts-with selector and loop through the results and tally up the text values casted to integers.
function GetSum(prefix) {
var sum = 0;
$("div[id^='" + prefix + "']").each(function(){
sum += parseInt($(this).text());
});
return sum;
}
var grid0Total = GetSum("grid0");
var grid1Total = GetSum("grid1");
Or if you wanted to take it a step further with a jQuery function:
jQuery.extend({
gridSum: function(prefix) {
var sum = 0;
if(!!prefix) {
$("div[id^='" + prefix + "']").each(function(){
sum += parseInt($(this).text());
});
}
return sum;
}
});
then you could write:
var grid0Total = jQuery.gridSum("grid0");
var grid1Total = jQuery.gridSum("grid1");
You could also use the map() function like so:
var sum = 0;
$("div[id^='" + prefix + "']").map(function(){
return sum += parseInt($(this).text());
});
return sum;
See them all in action here: http://jsfiddle.net/FpmFW/1/
Try:
function total(idPrefix) {
var total = 0;
$('div[id^="' + idPrefix + '"]').each(function() {
total += parseInt($(this).text());
});
return total;
}
var grid0total = total('grid0'),
grid1total = total('grid1');
See: http://jsfiddle.net/Au8Fr/
I'd give all grid divs one commmon class. Something like this:
<div class="grid" id="myGrids">
<div class="grid" id="grid10">5</div>
<div class="grid" id="grid11">0</div>
<div class="grid" id="grid12">0</div>
<div class="grid" id="grid13">1</div>
<div class="grid" id="grid14">0</div>
<div class="grid" id="grid15">0</div>
</div>
Now you can easily count their values:
var count=0;
$(".grid").each(function(){
count+=parseInt($(this).text())
})
You can loop through all of your grid0X divs like this:
var countOnes = 0;
$('div[id^=grid0]').each(function() {
if ($(this).text() === "1") {
++countOnes;
}
});
That finds all div elements whose ID starts with grid0 (so, grid00, grid01, etc.). The loop counts how many of them contain just the text "1", which is what I think you were after in your question; if not, the loop logic is easily manipulated.
Similarly, for grid1X, just change the selector to use 1 instead of 0.
Alternately, though, if these divs are in some kind of container, you could use a selector to find the container and then loop through its children, e.g.:
HTML:
<div id="grid0">
<div>0</div>
<div>0</div>
<div>0</div>
<div>1</div>
<div>0</div>
<div>0</div>
</div>
JavaScript:
$("#grid0 > div").each(...);
...and avoid having all those IDs.