The following snippet doesn't work.
var empty = $();
var divs = $("div");
empty.add(divs);
There is a div element in the HTML and it is added correctly to divs. But the divs collection is not added to the empty jquery object.
Any ideas what`s wrong with that?
.add won't change the original object. Try:
empty = empty.add(divs);
You can do
var empty = $.extend($(), $('div'));
Per Jquery doc,
The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:
var pdiv = $("p");
pdiv.add("div"); // WRONG, pdiv will not change
Related
I am working on a javascript code where I can clone an element, but also want to delete one on click. Cloning works, but I can't remove one.
I have the following elements.
<input list="accountsdeb" name="deblist[1]" id="deblist" autocomplete="off">
<input list="accountsdeb" name="deblist[2]" id="deblist" autocomplete="off">
And now I want to remove the last one on click (last = highest number).
function remove1() {
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
var elem = document.getElementsByName("deblist["+dbla+"]");
alert(dbla);
//var last = debelelast - 1;
elem.parentNode.removeChild(elem);
}
As an orientation I used to have a look on an example from W3S and Stack. I have also seen that this works:
var elem = document.getElementById("myDiv");
elem.parentNode.removeChild(elem);
But this is random and as you can see I have tried to include this in my code.
The error I get is:
Uncaught TypeError: Cannot read property 'removeChild' of undefined
at HTMLAnchorElement.remove1 (index.php:179)
Where's the problem in my code, where is my thinking wrong?
I see two issues in the piece of code you provided,
deblist is used as id for 2 elements which is not advisable and due to this document.querySelectorAll('#deblist').length returns 2 (I am not sure if you intending to do so)
document.getElementsByName() (check here) will return a NodeList which needs to be iterated in order to access any of the returned elements. So here you need to select the child element by giving its index. In your case elem will have one element for the matched name deblist[2] and hence you need to access it like elem[0] for selecting its parent and deleting its child.
So the updated the code would be,
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
// console.log('dbla', dbla);
var elem = document.getElementsByName("deblist["+dbla+"]");
// console.log('elem 0', elem[0]);
// console.log('elem parentNode', elem[0].parentNode);
//var last = debelelast - 1;
elem[0].parentNode.removeChild(elem[0]);
Check the fiddle here
If the inputs are part of a group they could share a name property or such, and the use of jQuery could help you do something like...
$("input[name='group1']").last().parent().remove()
Or if not part of a group then just....
$("input").last().parent().remove()
Can someone please explain to me, why
var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
Parent.appendChild(document.createElement("hi"));
Node.appendChild(Parent);
produces a different result from
var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
.appendChild(document.createElement("hi"));
Node.appendChild(Parent);
In the second snippet the element testingOne doesn't even get included. Why does the piping do this?
Your first example will result in
<testing><testingone><hi></hi></testingone></testing>
Parent will contain the testingOne and the hi element will be appended to it.
While the second example will result in
<testing><hi></hi></testing>
Because Parent will contain the hi element, which is returned by the appendChild method.
Maybe it's a silly question. But I really can't understand it.
I'm using the Jquery Cycle2. And after some personalization I got a simple problem.
I need to know what is the "Index" of my current slide.
On the plugin's website a found this line of code that perfectly works.
$('#cycle-1 .cycle-slide').click(function(){
var index = $('#cycle-1').data('cycle.API').getSlideIndex(this);
alert(index);
});
It gives me the right index. But I'm trying to catch this Index when another element is clicked. So I can't use the parameter (this).
Then I tried this.
$('.anotherelement').click(function(){
var mycycle = $('#cycle-1 .cycle-slide');
var index = $('#cycle-1').data('cycle.API').getSlideIndex($(mycycle));
alert(index);
});
It doesn't return my current slide index. It returns "-1". Does anyone knows how I should pass the Object (selector) as a parameter to the getSlideIndex() ?
Thanks a lot :D
You can use $('.cycle-slideshow').data('cycle.opts').currSlide to get the current slide index
$('.anotherelement').click(function(){
var index = $('.cycle-slideshow').data('cycle.opts').currSlide;
var currSliderNum = index+1;
alert(currSliderNum);
return false;
});
FIDDLE
In the first piece of code this is a DOM element and not a jquery object. Try this instead:
var index = $('#cycle-1').data('cycle.API').getSlideIndex(mycycle[0]);
However, presumably, you have multiple .cycle-slide elements. This will just get the first one. In your first code you have access to a single one since only one was clicked. You need to decide which one you want to target here.
This code should say enough: http://jsfiddle.net/dimadima/fLCCK/3/
// Append and return a newly created `div` element
$el = $('<div id="#test"></div>').appendTo($('body'));
// Now, try to find it:
// Nothing
var attempt1 = $('#test');
// Also nothing
var attempt2 = $('body').find('#test');
// Also nothing
var attempt3 = $('div#test');
// Returns both the pre-existing and dynamically appended divs.
var attempt4 = $('div');
Don't understand why I can't retrieve this div as in any of the first 3 attempts. The 4th attempt sort of retrieves it, but not in satisfactory manner. I feel like I've done this successfully a million times.
The # sign is for referencing the div. When you define it you need to omit it:
$el = $('<div id="test"></div>').appendTo($('body'));
You should use # when you want to call a object.
$el = $('<div id="test"></div>').appendTo('body');
var length_test = $('#test').length;
console.log(length_test);
//outputs 1
I have created an array of jquery objects that I want to hide when a particular click event is triggered. Instead of looping through the contents of the same array for each click event can I transform the array into a single object or something that I can just attach a method on to?
I have a current fiddle here: http://jsfiddle.net/hd5qa/13/
Sorry if this sounds vague, I'm not sure how to best explain this.
Kyle
Yes. You can create an empty jQuery object and then call .add on it for each element.
var all = $();
$.each(myArray, function(index, element) { all = all.add(element); });
// now you can use all to apply something to all of them
all.show();
all.hide();
// etc
See your updated demo on JSFiddle.
Yes, there are a couple ways to do it. You can select them all at once:
var colors = $('#blue, #red, #green, #black, ...');
You can combine the individual collections into a single collection
var $blue = $('#blue');
var $red = $('#red');
var $green = $('#green');
var $black = $('#black');
var $purple = $('#purple');
var $orange = $('#orange');
var collection = $blue.add($red).add($green).add(.....
Or you can just give all the elements a class="color" attribute
var collection = $('.color');
You can compose a jQuery object with the
.add()
method. Then call methods of your composed object like normal.
e.g.
var ALL=$('#blue').add('#red');
ALL.hide();
Why not give them all a class?
myArray.each(function() { $(this).addClass("myArrayClass"); });
Then you can just
$(".myArrayClass").hide();
You could also use classes to assign the same onclick event handler to all of the click buttons at once.