Use html() as append() - javascript

I want to use html() same as how it works with append()
function showResponse(response) {
var $list = $('#list');
var items = response.items;
$.each(items, function(id, el){
$list.html('el.id.videoId')
});
}
I dont know if anyone did understand it but what i want is
List1 = id1, id2 id3
List2 = id4 id5 id6
When List1 is listed, and List2 will be requested this must remove List1 and list List2
With append it makes the list just longer, but i want it to replace it with current

jQuery's html() replaces all the content every time you call it, so you're replacing the content on every iteration.
To only replace the content after the loop has completed you can do
function showResponse(response) {
var $list = $('#list');
var items = response.items;
var result = "";
$.each(items, function(id, el){
result += el.id.videoId;
});
$list.html(result);
}

Try this:
$list.html($list.html() + 'el.id.videoId');
jQuery.html() returns the current html in object
jQuery.html( data ) sets object html to data

Not sure why you want to use html() when append will do the job.
Empty the list it and append the new elements
$list.empty();
$.each(items, function(id, el){
$list.append("<li>" + id + "</li>");
});
If you want to use html(), than build a string with all the list items and set it at once.

Have you tried?
$list.empty().append('el.id.videoId');

Related

Do I have to use .each() for this?

I want to look up all the items with a certain selector and return all of their titles as quickly as possible. I know I can use .each() to loop through them and populate a variable, but I would like to use .join() if possible.
Here is how I would do it using .each()
var pop = "";
$("a").each(function(i,v){
var pop = pop + $(this).attr("title") + ',';
});
//now pop looks like: "title1,title2,etc"
How could I return all the titles in a CSV format using .join() ?
I tried this but it didn't work:
var pop = $("a").title.join(',');
You have to iterate the array, yes. But you can use map for this specific case:
var arr = $("a").map(function () { return $(this).attr('title') }).get();
var csv = arr.join(',');

Add text with a specific class to dropdown <select>

I want to
Get Text From Classes with class .pick and populate them into a dropdown #pingList
1) my Variable picker returns a long string, so I assume I need to create an array
2) var array I want the result to be ['x','y','z'] as I assume this is what I need in the next step.
3) I then want to add this to the dropdown with the text and val set.
I am pretty sure all I am missing is the array part. Looking for some help.
My Jquery Code and Live Demo http://jsfiddle.net/UUY5Z/1/
// Get text from Pick CLass
var picker = $('.pick').text();
// Make an Array from string result above
var array = //??
// Add this to the dropdown
$.each(array, function (val, text) {
$('#pingList').append($('<option></option>').val(val).html(text));
});
.text() method returns textContent of all of the selected elements as one string, you can use .map() method instead which returns an array:
var picker = $('.pick').map(function(i, elem) {
return "<option value='"+i+"'>" +
(elem.textContent || elem.innerText) + // == $(elem).text()
"</option>";
}).get(); // array of options (string)
$('#pingList').append(picker);
http://jsfiddle.net/JJsRd/
Here an other solution , using $.each() :
$.each($('.pick'),function(i, elem){
$('#pingList').append( "<option value='"+i+"'>"+ $(elem).text() +"</option>");
});
DEMO HERE
$('.pick').each(function(){
$('#pinglist').append(""+$(this).text()+"");
});
This should work for Above Case.
http://jsfiddle.net/sushilbharwani/uNpND/
I have updated in your demo page.. #http://jsfiddle.net/UUY5Z/7/
$(".pick").each(function(){
var val = $(this).text();
$('<option>').val(val).text(val).appendTo('#pingList');
});
You can achieve the same like this.
No need to make an array.
$.each($('.pick'), function (val, text) {
$('#pingList').append($('<option></option>').val($(this).text()).html($(this).text()));
});
JSFiddle For Same http://jsfiddle.net/sushilbharwani/uNpND/

how to loop though div and get each value

I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma

jQuery .html() of all matched elements

.html() function on class selector ($('.class').html()) applies only to the first element that matches it. I'd like to get a value of all elements with class .class.
You are selection all elements with class .class but to gather all html content you need to walk trough all of them:
var fullHtml;
$('.class').each(function() {
fullHtml += $(this).html();
});
search items by containig text inside of it:
$('.class:contains("My Something to search")').each(function() {
// do somethign with that
});
Code: http://jsfiddle.net/CC2rL/1/
I prefer a one liner:
var fullHtml = $( '<div/>' ).append( $('.class').clone() ).html();
You could map the html() of each element in a filtered jQuery selection to an array and then join the result:
//Make selection
var html = $('.class')
//Filter the selection, returning only those whose HTML contains string
.filter(function(){
return this.innerHTML.indexOf("String to search for") > -1
})
//Map innerHTML to jQuery object
.map(function(){ return this.innerHTML; })
//Convert jQuery object to array
.get()
//Join strings together on an empty string
.join("");
Documentation:
.filter()
.map()
.get()
.join()
$('.class').toArray().map((v) => $(v).html())
Samich Answer is correct. Maybe having an array of htmls is better!
var fullHtml = [];
$('.class').each(function() {
fullHtml.push( $(this).html() );
});
In case you require the whole elements (with the outer HTML as well), there is another question with relevant answers here : Get selected element's outer HTML
A simple solution was provided by #Volomike :
var myItems = $('.wrapper .items');
var itemsHtml = '';
// We need to clone first, so that we don’t modify the original item
// Thin we wrap the clone, so we can get the element’s outer HTML
myItems.each(function() {
itemsHtml += $(this).clone().wrap('<p>').parent().html();
});
console.log( 'All items HTML', itemsHtml );
An even simpler solution by #Eric Hu. Note that not all browsers support outerHTML :
var myItems = $('.wrapper .items');
var itemsHtml = '';
// vanilla JavaScript to the rescue
myItems.each(function() {
itemsHtml += this.outerHTML;
});
console.log( 'All items HTML', itemsHtml );
I am posting the link to the other answer and what worked for me because when searching I arrived here first.
If you turn your jQuery object into an Array you can reduce over it.
const fullHtml = $('.class')
.toArray()
.reduce((result, el) => result.concat($(el).html()), '')

How to create list in HTML dynamically?

In my jQuery mobile app, I want to display the result from a web service in a list. How do I create the list dynamically?
var arr = ["list", "items", "here"];
$("div").append("<ul></ul>");
for(var i in arr) {
var li = "<li>";
$("ul").append(li.concat(arr[i]))
}
Better yet,
$.each(
a ,
function(i,v) {
$("#target_id").append("<li>" + v + "</li>") ;
}
) ;
Where a is an Array of Objects for the list content, i is the index variable passed to the callback function by jQuery.each ($.each) and vis the value for that index.
For reference: http://api.jquery.com/jQuery.each/ .

Categories

Resources