Add multiple element using jquery each? [duplicate] - javascript

This question already has answers here:
Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?
(2 answers)
Closed 3 months ago.
I'm new here and I'd like to ask a question about jQuery.
i have some problem with jquery each, and i have code :
$("#search-submit").click(function(){
var item = $("<span>asdf</span>");
$("body").append(item, item);
}
I just can't figure out, why is this simple code don't work. Instead of print "asdf" twice, i just got one "asdf" printed each time i click the button..
this also don't work. this is so silly...
$("body").append(item);
$("body").append(item);
Thanks a lot... and sorry about my bad english
Denny.

You can append a jQuery object only one time, you can clone the object:
$("#search-submit").click(function() {
var item = $("<span>asdf</span>");
$("body").append(item, item.clone());
})
Or append a string:
$("#search-submit").click(function() {
var item = "<span>asdf</span>";
$("body").append(item, item);
})
http://jsfiddle.net/yKyAL/

You can use clone
$("#search-submit").click(function() {
var item = $("<span>asdf</span>");
$("#test").append(item.clone(), item.clone());
});​
Check the fiddle here

Related

JavaScript - cloneNode gives different result [duplicate]

This question already has answers here:
Javascript clone node is not copying all values from cloned to new object
(3 answers)
Closed 5 years ago.
I am trying to clone the form before submition in JavaScript using cloneNode. The original form has an answer for a selected value but not the cloned one. Following is the code.
encodeHTMLCollectionToBase64(document.forms['formen']).submit();
function encodeHTMLCollectionToBase64(form) {
encryptedForm = form.cloneNode(true)
Array.from(encryptedForm).forEach(function(item) {
if (item.childElementCount > 0) {
for(var i=0;i < item.childElementCount;i++) {
item[i].value = btoa(encodeURIComponent(item[i].value));
}
}
else {
item.value = btoa(encodeURIComponent(item.value));
}
});
encryptedForm.style.visibility = 'hidden';
document.body.appendChild(encryptedForm);
return encryptedForm ;
}
Upon inspection I found that the encryptedForm (cloned form) has empty value for one select element but it is there in form (original form). Why is that?
Am i doing something wrong here?
The form's selections are saved in the browser, not in the form's DOM elements, so when you clone it, the selections will not be copied over. It's possible to copy the selections over if you use JavaScript to manage the 'selected' prop on all of your form elements, or you could store the selections in a separate variable and reapply them later.

Different ways of creating a div [duplicate]

This question already has answers here:
What is the most efficient way to create HTML elements using jQuery?
(12 answers)
Closed 7 years ago.
Is there any significant difference in how the new DOM element is created? Are there any advantages/disadvantages of using one way over another or does it come down to personal preference? I usually use the first way and only recently found out about the second one.
var test1 = $('div#test1'),
test2 = $('div#test2')
;
// first way
$('<div/>')
.addClass('mainClass subClass')
.attr('id', 'someId2')
.attr('data-extra', 'extraInfo')
.text('some text')
.appendTo(test2)
;
// second way
$('<div/>',
{
'class': 'mainClass subClass',
'id': 'someId1',
'data-extra': 'extraInfo',
'text': 'some text'
})
.appendTo(test1)
;
I think different ways are differ in performance , put not completely sure the from the perfect answer
i am using pure javascript
var element = document.createElement("div");
var elementContent = document.createTextNode("My div");
element.appendChild(elementContent);
// add div to body
document.body.appendChild(element);
Second example will be faster compared to first.
In case of first. The object is created and returned. And then you are using jquery methods which gets the jquery object of element everytime and sets the new classes/attributes.
In case of second approach, it iterate over the collection of properties to create the dom element along with those attributes and classes.

Getting the first item in an [word, word] [duplicate]

This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow

how to select my first child in jQuery [duplicate]

This question already has answers here:
jQuery first child of "this"
(11 answers)
Closed 10 years ago.
I'm having a bit of trouble selecting the first child in jQuery. I'm trying to do this to avoid having LOTS of if statements. Basically, you click on a button. This class selector is setup to handle the click in my JS. Once you go into the JS, I want to get the child of the item that was just clicked, but I'm not having any joy.
Here's what I have in my JS:
$('.itemClicked').click(function(){
var id = $(this).attr('id').first();
// it can't find the method first() here. If I just find the id, I get the
// correct ID of what I just clicked.
var test = id.first();
// I tried the above to seperate the ID from the first() method request
// no joy with this either.
test.toggleClass("icon-tick");
// this is my ultimate aim, to toggle this icon-tick class on the item
// clicked.
});
Thanks in advance if you can help me out here. I'm probably just doing something stupid but I'm struggling to realise what that is.
Your current version doesn't work because .attr('id') just returns the ID as a string, not a jQuery object. Also, .first() returns the first item from a jQuery collection, not their children.
So, you just want:
var test = $(this).children().first();
or:
var test = $('>:first-child', this);
or:
var test = $(this).children(':first');
or (on newer browsers):
var test = $(this.firstElementChild);
In a jsperf test with Chrome 25 the .firstElementChild method was incredibly fast, but it's not available on MSIE < 9. The .children().first()was the fastest portable option, and the>:first-child' method was very, very slow.
Perhaps
$('.itemClicked').click(function(){
$(':first-child',this).toggleClass('icon-tick');
});
is what you're after.
Live example: http://jsfiddle.net/ySMLG/
If all that you want to do is toggle the class "icon-tick" on the item that was click, then this will work:
$('.itemClick').click(function () {
$(this).toggleClass('icon-tick');
});
The statement:
$(this).attr('id').first()
doesn't work because the attr() method returns the value of the attribute, not the jQuery object, so it is not chainable.

How to remove object from inside .each() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to remove a property from an object?
I am comparing two JSON objects and then deleting the old items from a list with this code:
dangerousPeople = ({1:{title:"Jackie Chan", user:"Jackie"}, 2:{title:"Chuck Norris", user:"Chuck"}, 3:{title:"Britney spears", user:"Britney"}});
newDangerousPeople = ({1:{title:"Jackie Chan", user:"Jackie"}, 3:{title:"Britney spears", user:"Britney"}});
$.each(dangerousPeople, function(index)
{
if(!newDangerousPeople[index]){
$('#dangerousPeople #id'+index).slideUp("normal", function() { $(this).remove(); } );
delete dangerousPeople.index;
}
});
The part of the script that slidesup the element works, but deleting the element from the object I can't make it work.
I tried with delete dangerousPeople.index but doesn't work, also tried delete $(this) but no luck either.
So how should I remove the element from itself?
Try:
...
delete dangerousPeople[ index ];
...

Categories