.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()), '')
Related
I am trying to filter an array with grep to apply CSS. My code is like below.
var depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var found_p = $.grep(depos, function(v) {
return jQuery.inArray(v.innerText,chkd);
});
The first issue is that found_p is not filtering the needed array values from chkd. After filtering it, how can I apply CSS? I tried like below but it fails
$(found_p[0]).css('background-color', 'red');
Can anybody help me out with this.
Assuming from your code that you're trying to find the elements that have innerText matching a value in the chkd array, you can use the filter() method. Try this:
var $depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var $found_p = $depos.filter(function() {
return $.inArray($(this).text(), chkd) != -1;
});
The $found_p variable will then hold a jQuery object with all matched elements. You can apply CSS to them like this:
$found_p.css('background-color', 'red');
Example fiddle
However, I would suggest using CSS classes instead of adding inline styles as it is much better practice.
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');
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/
I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);
I working on something where I need two functions.
1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array.
['foo-a','foo-b','foo-d']
2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array.
Does this element have class foo-a, foo-b or foo-d?
For the first part, I'd use map and get:
var activeGroups = $('#parent .active').map(function() {
return this.id;
}).get();
This gives you an array of id values (say, ['foo-a', 'foo-d']). You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector) using join:
var activeSelector = '.' + activeGroups.join(', .');
This makes a valid jQuery selector string, e.g. '.foo-a, .foo-d'. You can then use this selector to find the elements you want using find:
var activeEls = $('#secondParent').find(activeSelector);
You can then do whatever you need to with activeEls.
var active = $("#foo").find(".active").map(function() {
return this.id;
}).get();
$("#anotherParent *").each(function() {
var that = this;
var classes = $(this).attr("class");
if(classes.indexOf(" ") !== -1) {
classes = classes.split(" ");
} else {
classes = [ classes ];
}
$.each(classes, function(i, val) {
if($.inArray(val, active)) {
// this element has one of 'em, do something with it
$(that).hide();
}
});
});
There's always .is('.foo-a, .foo-b, .foo-d'). Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint).