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"));
});
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);
});
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/
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
I am trying to clone multiple divs on my page by using the jQuery .clone() method. The problem is, as soon as a div is cloned, it needs to have a unique ID. The cloned ID has to be there too. I was thinking I could keep the old ID and then just add a number on, increasing as more div's are on the page.
Example: base ID = one, so div one would be id, then div two would be id-2, then div three would be id-3, etc.
Is this possible? My attempt at this is below:
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
$(target).clone().attr("id",id + $(id).size()).attr("class","drag").appendTo("body");
});
Each a tag looks like this:
One
Two
Then the cloned element looks like this:
<div class="drag base" style="background-color:blue" id="one"></div>
<div class="drag base" style="background-color:green" id="two"></div>
See this: http://jsfiddle.net/3tu7V/1/
$(function(){
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
var click = $(target).data("clicked") || 0;
$(target).data("clicked", ++click);
$(target).clone().attr("id",id + click).attr("class","drag").appendTo("body");
});
});
I think this does what you want according to your comment:
"Ah, is there any way for the element ID to be reset when the base ID is unique? Ex.) "If you clone div "one", it will produce "one-1", then "one-2", but if you then clone div "two", it will produce "two-3", not "two-1""
i think in ur case $(id).size() will always be = 2. (only the last one and its clone will have the same id)
why don't you use a global variable var clickNumber that you increment each time.
your code will be
var clickNumber = 0;
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
clickNumber ++;
$(target).clone().attr("id","id-" + clickNumber).attr("class","drag").appendTo("body");
});
See this live example
var increment = 2;
$('a').live('click', function() {
$(this).clone().attr('id','id-' + (increment++)).appendTo('body');
});
Result:
Revised answer:
You can use the jQuery attribute starts with selector to keep a track of the clones, and their counts:
$("a").click(function() {
var targetId = $(this).attr("href").substring(1); // "one", "two"
var count = $("div[id^=" + targetId + "]").length; // initial value will be 1
$("#" + targetId).clone().attr("id", targetId + '-' + count).attr("class", "drag").appendTo("body");
});
Demo
You could do something like this:
$('a').addClass('link');
$('body').on('click', 'a', function() {
$(this).clone(true).attr('id', 'id-' + $('.link').length).appendTo('body');
});
Demo: http://jsfiddle.net/Em8PE/1/
I'm trying to get all the found elements within a <div>, but by default it stops when it found the first occurrence, but I want it to list every found element's id value.
So this doesn't work:
listy = $("DIV").find("SPAN").attr("id");
I've been experimenting with .get and .map, but I think they're not what I want..
listy = $("div").find("span").map(function(){
return this.id;
}).get();
Without find is even better:
listy = $("div span").map(function(){
return this.id;
}).get();
Live DEMO
If you want only <span> with id attribute defined, change the selector to:
$(div span[id]).map(...)
If you want all the ids as a string:
listy = $("div span").map(function(){
return this.id;
}).get().join('');
The parameter of join is the delimiter, e.g. .join('-') or .join(',') or without: .join('')
Maybe this way?
var ids = [];
$("div span").each(function() {
if (this.id) {
ids.push(this.id);
}
});
attr() method will always return first elements attribute only.
var listy = '';
$("div span").each(function(){
listy += this.id ;
});
jsBin demo
Or like:
var listy = []; // create array
$("div span[id]").each(function(){ // span with ID data
listy.push( this.id ); // push ID names into array
});
// Now use listy.join(); to see the list
// you can also do: listy+'' to transform it into string.
jsBIn demo 2