I want to pull into an array the classes of all of the <img> in a particular <div> and then use those classes to delete the first <img> that shares that class in a different <div>.
So far, I have this that calls the original array:
var class = $('.frame div img').each(function() {
return $(this).class;
}).get();
class.forEach(function(entry) {
console.log(entry);
});
The log outputs a list of the <img></img> lines.
After that, I get stuck.
//Iterate through array and delete first <img> in #grid that has the same class, limit one per iteration.
// var img_class = $.each(class, function(key, value) {
// console.log(value);
// return $(this).attr('class');
// });
$('#grid img').each(function(){
if($(this).attr('class') == img_class){
$(this).remove();
}
});
The goals are:
Getting an array of classes into the img_class variable
Delete only the first <img> as it iterates through each class in the array
Thanks!
I am not sure if I understood it right but would something like this be of any help?
var firstIDs = "";
$('.frame div img').each(function() {
firstIDs += $(this).attr('id') + ",";
});
var SplitIDs = firstIDs.split(",");
$('#grid img').each(function(){
for(var i = 0; i < SplitIDs.length; i++) {
if($(this).attr('id') == SplitIDs[i]){
$("#grid img #"+$(this).attr('id')+":first").remove();
}
}
});
I would suggest to use some other attribute than class, eg. 'data-type'.
With the collected attribute values (e.g. 'types' array) do:
var $grid = $('#grid');
// iterate over collected types
types.forEach(function(type)) {
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
}
You could also do all in one rush:
// iterate over source <img> set
$('.frame div img').each(function() {
// get current images type-attrib
var type = $(this).attr('data-type');
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
});
Try
$(function() {
var classes = $.map($(".frame div img"), function(v, k) {
return [$(v).attr("class")];
});
var d = [];
console.log($("#grid img").length);
$.each($("#grid img"), function(k, v) {
if ( classes.hasOwnProperty($(v).attr("class")) ) {
d.push(v); $("body").find($(d.slice(0, 1))).remove();
};
});
console.log($("#grid img").length);
});
jsfiddle http://jsfiddle.net/guest271314/yv95C/
Related
I have this JQuery function:
var objects = document.querySelectorAll('object');
// Iterate through objects
$('object').each( function() {
var link = $(this).attr('data');
$(this).append('click here');
});
It goes through all <object> items in a page and appends a link to the end of them (all of the objects in this case are used to create an embed document.) However, I want to edit the function so that it also edits an attribute in the object tag, preferably changing the name attribute, and also add an if statement to check to see if the object tag contains this new name.
You can use .attr() to get/set the name attribute, also you can use .is() along with attribute selector
// Iterate through objects
var $objects = $('object');
$objects.each(function() {
var $this = $(this);
$this.append('<a href="' + $this.attr('data')
'">click here</a>');
var nametoset = ''; //some logic to find the name
if ($objects.is('[name="' + nametoset + '"]')) {
//name already exists so do something
} else {
$this.attr('name', nametoset);
}
});
$('object').each( function() {
var link = $(this).attr('data');
var newlink = $('click here');
newLink.attr("name","jonny");
$(this).append(newLink);
});
OR
$('object').each( function() {
var link = $(this).attr('data');
var newname = "jonny";
var newlink =$ ('click here');
$(this).append(newLink);
});
Notice that my first two table Data (Apple and Orange) are set to read-only. And I do have function for dynamic adding of row.
see this FIDDLE FOR DEMO
If the user click the Save button, all input field that detect duplicate of data from database or last duplicate of data from row which dynamically added, border-color will change to red.
$("#save").off("click").on("click",function(){
var $rows = $('#myTable tbody tr:not(:hidden)');
$rows.each(function(){
var $id = $(this).find('td input[type=\'text\']');
alert($id.val());
//Im stuck here, for checking column data is duplicate.
});
});
Im looking forward on using Jquery filter , like this :
$( "li" ).filter( "DUPLICATE DATA()" ).css( "border-color", "red" );
I am assuming you want to target the "Name" column, although you could easily change this to target all columns.
Basically, you want to go through the input elements, keeping a reference to the values you've already reviewed:
$("#save").off("click").on("click",function(){
var existing = [];
var duplicates = $('#myTable td:nth-child(3) input').filter(function() {
var value = $(this).val();
if (existing.indexOf(value) >= 0) {
return $(this);
}
existing.push(value);
});
duplicates.closest('tr').css('background-color', 'red');
});
JSFiddle
Edit: To avoid marking a read-only line as a duplicate, the process is a little less straightforward
$("#save").off("click").on("click",function(){
// Clear status of all elements
$('#myTable tr').css('background-color', 'none');
// Get all values first (Apple, Orange, etc) as strings
var allValues = $('#myTable td:nth-child(3) input').map(function() {
return $(this).val();
}).toArray();
// Iterate unique values individually, to avoid marking a read-only input as duplicate
var processedValues = [];
for (var i = 0; i < allValues.length; i++) {
var value = allValues[i];
if (value != '' && processedValues.indexOf(value) >= 0) continue;
var inputs = $('#myTable td:nth-child(3) input').filter(function() { return $(this).val() == value; });
// Check if this value is in one of the readonly
var readOnlyInput = inputs.filter(function() { return $(this).is('[readonly]'); });
if (readOnlyInput.length) {
inputs.not(readOnlyInput).closest('tr').css('background-color', 'red');
} else {
inputs.not(':first').closest('tr').css('background-color', 'red');
}
processedValues.push(value);
}
});
Updated JSFiddle
I have an array with buttons:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
If one of them is clicked I want to get their index-value in the array:
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf(this); //($(this)) doesn't work either!
});
This doesn't work.
I used the jQuery method .index() instead:
var y = $(this).index();
but I'd rather not because the order of the buttons in the html is not the same as in the array.
Thanks for your help!
Since your array has IDs with hashes, then you need to search for the ID with a hash, not the element itself. There are two solutions:
Make your button array reference objects instead of IDs
var buttonnumber = [$("#btn1"), $("#btn2"), $("#btn3"), $("#btn4"), $("#btn5")];
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf($(this));
});
or do the indexOf against the id of the object you are clicking:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf("#" + this.id);
});
You can also write that click selector as:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
$(buttonnumber.join()).click(function() {
var y = buttonnumber.indexOf("#" + this.id);
});
In modern browsers, you also no longer need jQuery for something like this:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
// cast nodelist that's returned from querySelectorAll to array
Array.prototype.slice.call(document.querySelectorAll(buttonNumber.join()))
.forEach(el => {
el.addEventListener("click", (event) => {
let y = buttonnumber.indexOf("#" + this.id);
});
})
buttonnumber.indexOf(this);
Supposed to be
buttonnumber.indexOf('#' + this.id);
this corresponds to the DOM element. Need to get the id of that element and get the index based of of it.
Get the clicked items ID attribute with $(this).attr('id') and get your index from the string...
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf($(this).prop("id"));
});
I need to be able to get an unqiue selector for each element on a page.
For example, when I click on an element I want to do something like this:
$(document).click(function(){
var sel = getUniqueSel(this);
});
So, after storing the sel value in a DB I can get that value and simply access the element by
var el = $(sel);
I can't change and don't know anything about the HTML structure of the page and I can't simply add unique ID's (using JS) to every element as this would be inefficient.
Another approach might be to wander up the dom tree and create a path to the element, which you can save and use it later as a selector again, although that might not be bulletproof, but maybe its a point where you can start off.
Edit: Updated the Answer with your suggestion in the comment, now it returns the id if available
Just visit the example on JSBin And click the document twice.
but notice what gets highlighted..
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
if (node[0].id) return "#" + node[0].id;
while (node.length) {
var realNode = node[0],
name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
var sel;
$(document)
.click(function (e, a) {
if (!sel) {
sel = $("#comment-21702402")
.getPath();
alert("Path is: " + sel + ", hiding the Element -> Click again to highlight");
} else {
$(sel)
.css("background-color", "yellow");
}
});
One way to do this is to get all the information you can get on the element that was clicked.
So when you save it to the database you can save it as a text for example:
If the element you clicked on is: <div> I'm a div </div>
$(document).click(function(){
var tagName = $(this).prev().prop('tagName');
var attributes = {};
if( this.length ) {
$.each( this[0].attributes, function( index, attr ) {
attributes[ attr.name ] = attr.value;
} );
}
var elText=$(this).html();
saveToDB(tagName,attributes,elText);
});
You can later find the element using the attributes you have or simply use
$(tagName+'['+attribute+'="'+value+'"]:contains("'+elText+'")')
I think this should help
Goal: Get a specific HTML element ul's id value from a ul class called SBUpdater
Purpose: My program contains several server url's and parses specific information that I need from each server url. Each id of a ul contains the value of a server url. I need to take this ID value so i can update that specific ul tag and update the content on the screen (without refreshing the page).
In a php file I have the following:
Example Code:
<ul id="http://server1.com" class="SBUPdater">
<li> ... </li>
</ul>
<ul id="http://server2.com" class="SBUPdater">
<li> ... </li>
</ul>
All I need is a method of getting this id value from the ul tags.
Known:
Tag = ul
Class = SBUpdater
ID = ?
What I would like is to retrieve every ul's id value, take all ul id's, perform a function with them, and then repeat the process every 10 seconds.
You can use .map(), though your IDs are invalid, like this:
var idArray = $(".SBUPdater").map(function() { return this.id; }).get();
I'd use a data attribute though, like this:
<ul data-url="http://server1.com" class="SBUPdater">
And script like this:
var urlArray = $(".SBUPdater").map(function() { return $(this).attr("data-url"); }).get();
Or, if you're on jQuery 1.4.3+
var urlArray = $(".SBUPdater").map(function() { return $(this).data("url"); }).get();
With prototype library you would do this:
$$('.SBUPdater').each(function(){
new Ajax.PeriodicalUpdater(this, this.getAttribute('data-url'), {
frequency: 10 // every 10 seconds
});
});
Each ul element would use the data-url (not id) attribute to hold the URL of your server script. That script would then return the new content of the appropriate ul element.
Thanks to Nick Craver for excellent suggestion
$('ul.SBUPdater').each(function(){
alert(this.id);
});
Hmm maybe something like this:
var urls = new Array();
var count = 0;
$('.SBUPdater').each(function() {
urls[count] = $('.SBUpdater').attr('id');
count++;
}
for(var i = 0; i < count; i++) {
//do something with urls[i];
}
It could even be inside of the each function.
setInterval( function(){
$('ul.SBUPdater').each(function(){
// use this.id
console.log(this.id);
})
}, 10000 );
this should do it..
In jQuery this would be as easy as:
var ids = $('.SBUPdater').map(function(el) {
return el.id;
});
console.log(ids); // ids contains an array of ids
To do something with those ids every 10 seconds you could setInterval:
window.setInterval(function() {
$.each(ids, function(id) {
console.log(id);
});
}, 10 * 1000);
EDIT:
function GetULs() {
var ULs = document.getElementsByTagName("UL");
var IDs = new Array();
for(var i = 0; i < ULs.length; i++) {
if(ULs[i].className == "SBUPdater") {
IDs.push(ULs[i].id);
}
}
return IDs;
}
This function will return an array of all of the element IDs that you are looking for. You can then use that array for whatever you need.