I'm very new to this, I'm looking to get the data-rating value of each line of HTML and output the same image a multiple amount of times for each line, dependent on each value, using jQuery/Javascript.
Here's a sample of the HTML:
<div class="review-value" data-rating="5"></div>
<div class="review-value" data-rating="7"></div>
How can I best do this?
One of the way to do it.
Get the attribute for each div.
Run the loop that many times and add an image in each iteration
$('.review-value').each(function() {
for (var i = 0, len = parseInt($(this).attr("data-rating")); i < len; i++) {
$('<img src="#" />').appendTo($(this))
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="review-value" data-rating="5"></div>
<div class="review-value" data-rating="7"></div>
You can use this code:
$('.review-value').each(function (index, value) {
alert('div' + index + ':' + $(this).attr("data-rating"));
});
Data is HTML's attribute. you can use that as well with Jquery each loop and store the value in Array
var getRating = [];
$('.review-value').each(function () {
getRating.push($(this).data("rating"));
});
alert(getRating);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="review-value" data-rating="5"></div>
<div class="review-value" data-rating="7"></div>
JQuery has data() that can help you get the value of any data attributes:
$(document).ready(function() {
$(".review-value").each(function() {
console.log('Rating: ' + $(this).data('rating'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="review-value" data-rating="5"></div>
<div class="review-value" data-rating="7"></div>
Related
Let's say we have element with custom attribute
... bind-html="varName" ...
I want to find all elements with attribute beginning with "bind-",
then get second part of it's name, which is unknown, in this case "html".
And at last get it's value "varName".
How do i achieved this with Jquery? I don't want to use second attribute to describe attibute to bind (like .. bind="varName" attr="html" ..)
You can use a loop through each object's attributes this.attributes and use the attribute's name and value properties.
Running example:
$("input").each(function() {
$.each(this.attributes, function() {
if (this.name.indexOf('bind-') == 0) {
console.log(this.name + ' has the value: ' + this.value);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input bind-koby='hello'>
<input bind-douek='stack'>
<input will-not-show='yes'>
<input bind-hello='overflow'>
well that what you are looking for like
<div bind-html="varName">hi there i am </div>
well hi thats me
var namer = $(" *[attr*='bind']").text();
console.log(namer);
<div class="bindable" data-bind="html:varName1"></div>
<div class="bindable" data-bind="css:varName2"></div>
<div class="bindable" data-bind="js:varName3"></div>
<div class="bindable" data-bind="whatEver:varName4"></div>
(function(){
let bindables = $('.bindable');
bindables.each(function(){
let bindData = $(this).data('bind');
let bindDataArray = bindData.split(":");
console.log(bindDataArray);
});
}());
now u will get array with data u want
You can get all elements and their attributes which contain bind- by using jquery .properties and .indexOf() like following example.
// $("*") selects all elements in your html
$("*").each(function() {
$.each(this.attributes, function() {
// checks whether element has an attribute starts with "bind-" or not
if(this.specified && this.name.indexOf("bind-") !== -1) {
console.log("Attr Name: "+ this.name + " Attr Value: " + this.value)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span bindNot-html="bindNot">element1</span>
<div bind-html="varName1">element2</div>
<a bind-html2="varName2">element3</a>
<div bind-html3="varName3">element4</div>
<span bindNot-html="bindNot">element5</span>
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 want to find div element that contain custom attribute mod than append that div to list item. But first I have to remove divs that contain duplicate mod value. Here's what I have done
<div class="list"></div>
<div class="container">
<div mod="dog"></div>
<div mod="man"></div>
<div mod="woman"></div>
<div mod="dog"></div>
<div mod="bird"></div>
<div mod="insects"></div>
<div mod="dog"></div>
</div>
this is my script
modArr($('.container').find('[mod]'))
function modArr(el){
var filterArray = [] // store mod
, modNames = [] // store mod value
, arrIndex = [] // store non duplicate index
, li = [] // store
modArray = el
// store mod value
for(var i=0; i < modArray.length; i++){
modNames.push($(modArray[i]).attr('mod')) // get mod value from div
}
// search for non duplicate mod value and get the index of none duplicate mod
for(var i=0; i < modArray.length; i++){
if(filterArray.indexOf(modNames[i]) === -1){
filterArray.push(modNames[i])
arrIndex.push(i) // push non duplicate index value
}
}
filterArray = [] // reset filterArray
// push module from modArray to filterArray using index in arrIndex
for(var i=0; i < arrIndex.length; i++){
filterArray.push(modArray[arrIndex[i]])
}
// push to li array
$.each(filterArray,function(i,el){
li[i] = '<li>'+ el.outerHTML +'</li>'
})
$('<ul></ul>')
.append(li.join(''))
.appendTo('.list')
}
What you can see is that I've used to many loops, is there any simple way to do this. Thanks!
We can use an object as a map for checking duplicates, see comments (I've added text to the mod divs so we can see them):
modArr($('.container').find('[mod]'));
function modArr(elements) {
// A place to remember the mods we've seen
var knownMods = Object.create(null);
// Create the list
var ul = $("<ul></ul>");
// Loop the divs
elements.each(function() {
// Get this mod value
var mod = this.getAttribute("mod");
// Already have one?
if (!knownMods[mod]) {
// No, add it
knownMods[mod] = true;
ul.append($("<li></li>").append(this.cloneNode(true)));
}
});
// Put the list in the .list element
ul.appendTo(".list");
}
<div class="list"></div>
<div class="container">
<div mod="dog">dog</div>
<div mod="man">man</div>
<div mod="woman">woman</div>
<div mod="dog">dog</div>
<div mod="bird">bird</div>
<div mod="insects">insects</div>
<div mod="dog">dog</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
We can also just use the DOM to check for duplicates, but it's a bit slower (not that it matters for the number of elements here):
modArr($('.container').find('[mod]'));
function modArr(elements) {
// Create the list
var ul = $("<ul></ul>");
// Loop the divs
elements.each(function() {
// Get this mod value
var mod = this.getAttribute("mod");
// Already have one?
if (ul.find('div[mod="' + mod + '"]').length == 0) {
// No, add it
ul.append($("<li></li>").append(this.cloneNode(true)));
}
});
// Put the list in the .list element
ul.appendTo(".list");
}
<div class="list"></div>
<div class="container">
<div mod="dog">dog</div>
<div mod="man">man</div>
<div mod="woman">woman</div>
<div mod="dog">dog</div>
<div mod="bird">bird</div>
<div mod="insects">insects</div>
<div mod="dog">dog</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: I used this.cloneNode(true) rather than outerHTML because there's no need to take a roundtrip through markup. If you want more jQuery there, it's $(this).clone(); ;-) Similarly, if you don't like this.getAttribute("mod"), there's $(this).attr("mod").
I'd be remiss if I didn't point out that mod is an invalid attribute name for div elements. You can use any name you want starting with data-, though, so perhaps use <div data-mod="dog"> instead.
Try this, only adds if an element with mod is not already in list:
$('.list').append('<ul>');
$('.container [mod]').each(function(index, el) {
if($('.list [mod=' + $(el).attr('mod') + ']').length === 0) {
$('.list ul').append($('<li>' + el.outerHTML + '</li>'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="list"></div>
<div class="container">
<div mod="dog">Dog1</div>
<div mod="man">Man1</div>
<div mod="woman">Woman1</div>
<div mod="dog">Dog2</div>
<div mod="bird">Bird1</div>
<div mod="insects">Insect1</div>
<div mod="dog">Dog3</div>
</div>
I'm trying to find the deepest element in the specified divwith jquery. But the code which used is producing the error TypeError: parent.children is not a function.
I found this code from this link
the code is :
function findDeepestChild(parent) {
var result = {depth: 0, element: parent};
parent.children().each( //Here I getting the error TypeError: parent.children is not a function
function(idx) {
var child = $(this);
var childResult = findDeepestChild(child);
if (childResult.depth + 1 > result.depth) {
result = {
depth: 1 + childResult.depth,
element: childResult.element};
}
}
);
return result;
}
---------------------------------------------------------------------------------------
$(document).on('keypress','#sendComment', function(e) {
if(e.keyCode==13){
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
alert(item);
}
});
And my divs are :
<div id="S04" class="snew" style="display: block;">
<div class="author-image"></div>
<span>xyz shared the image xyz</span>
<div class="s-content">
<div class="s-message"></div>
<div class="shpicture">
<img class="SharedImage" width="100%" height="100%" data-shareid="1" data-alid="1" data-id="1" alt="xyz" src="data:image/jpeg;base64,">
</div>
</div>
</div>
<div class="SPcommentbox">
<div class="comment">
<div class="commenter-image"></div>
<div class="addcomment">
<input class="commentbox" type="text" placeholder="Write a comment...">
</div>
</div>
</div>
I need to find the img from these.
please anyone help me .... Thanks ...
To get the deepest nested elements, use
$("#" + parent).find("*").last().siblings().addBack()
http://jsfiddle.net/6ymUY/1/
you can then get the id data attribute with
item.data("id")
http://jsfiddle.net/6ymUY/2/
full code:
function findDeepestChild(parent) {
return $("#" + parent).find("*").last().siblings().addBack();
}
var item=findDeepestChild("S04");
console.log(item)
console.log(item.data("id"));
You're calling it with a string, but it's expecting a jQuery instance.
Instead of
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
you probably want
var item=findDeepestChild($('#findbefore').prev('.snew'));
You are passing in itemId, which is the ID attribute of a given element. I think what you meant to pass was the element itself. Just remove the attr call, leaving this:
var item = findDeepestChild($("#findbefore").prev(".snew"));
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.