Count html elements in ajax returned data - javascript

I've got a jquery $.ajax call that returns a set of html from data.html which is like;
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
I'd like to count the amount of elements that have a class of .blah and i'm not sure how to do this.
I've tried:
data.html.getElementsByClassName('blah').length
but that obviously doesn't work!
Any suggestions gratefully received!!

Try utilizing .hasClass()
var data = {};
data.html = '<div class="blah item item-wrapper print"></div>'
+ '<div class="blah item item-wrapper digital"></div>';
var len = $.grep($.parseHTML(data.html), function(el, i) {
return $(el).hasClass("blah")
}).length;
$("body").html(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

You should be able to do this using either .filter() or .find(), depending on the exact format of your returned HTML. If the format is is exactly as you have stated, then the following should work:
$.get("data.html", function(data) {
var length = $(data).filter(".blah").length;
});
If there is some sort of wrapper element around your items with class blah, then you would use .find():
$.get("data.html", function(data) {
var length = $(data).find(".blah").length;
});

$('.blah','context').length
Replace context by object in which you want to search

Related

Splitting a JavaScript string from XML and wrapping in HTML element

I'm working on displaying an RSS feed in a website through the use of jQuery and AJAX. One of the strings from the source XML file are wrapped in a <category> tag, and there are multiple of these returned. I'm getting the source data like follows:
var _category = $(this).find('category').text();
Because there are multiple categories returned with this method, say the following:
<category>Travel</category>
<category>Business</category>
<category>Lifestyle</category>
I'm getting strings returned like so:
TravelBusinessLifestyle
My end goal is to see each of these separate strings returned and wrapped in individual HTML elements, such as <div class="new"></div>.
I did end up trying the following:
var _categoryContainer = $(this)
.find('category')
.each(function () {
$(this).wrap( "<div class='new'></div>" );
});
among quite a few other variations.
This is all being appended to a HTML structure similar to the following.
// Add XML content to the HTML structure
$(".rss .rss-loader")
.append(
'<div class="col">'
+ <h5 class="myClass">myTitle</h5>
+ _category
+ "</div>"
);
Any suggestions would be much appreciated!
if it's a simple html which is mentioned in a question. you can use something like below.
var html="<category>Travel</category><category>Business</category><category>Lifestyle</category>"
var htmlObj=$.parseHTML(html);
var container=$("#container")
$.each(htmlObj,function(i,o){
container.append("<div class='new'>"+o.innerText+"</div>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>
Same as first answer, but without jquery
let container = document.querySelector('div#container');
document.querySelectorAll('category').forEach(element => {
let div = document.createElement('div');
div.innerText = element.innerText;
container.appendChild(div);
})
<category>Travel</category><category>Business</category><category>Lifestyle</category>
<div id="container"></div>

replace set of strings in array

Using $('div#top_container').html(), I get the following as an example:
<div class="top" id="top_container">
<div class="example">First</div>
<div class="example">Second</div>
</div>
giving...
<div class="example">First</div>
<div class="example">Second</div>
Here, using .replace(), I want to replace <div class="example"> with *%^% (random set of characters) and remove </div>:
var content = $('div#top_container').html();
var clean_1 = content.replace('<div class="example">','*%^%'); //add $*!#$
var clean_2 = clean_1.replace('</div>',' '); //remove </div>
giving...
console.log(clean_2); --> *%^%First*%^%Second
Now, the number of example div elements can vary and I need to first find out how to target them all. Also is there a cleaner way to target both <div class="example"> and </div> at the same time?
EDIT:
I am not looking to change the html itself, but rather have the edited version as a variable that I can do stuff with (such as send it to php via ajax).
How would I do this?
Use replaceWith() method with a callback and generate prefered text string by getting text content using text() method.
$('div.example').replaceWith(function(v) {
return '%^%' + $(this).text();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="example">First</div>
<div class="example">Second</div>
</div>
UPDATE: If you don't want to update the original element then use clone() and do the remaining thinks on the cloned element.
var res = $('#parent')
// clone element
.clone()
// get element with `example` class
.find('.example')
// update content
.replaceWith(function(v) {
return '%^%' + $(this).text();
})
// back to previos selector and get html content
.end().html();
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="example">First</div>
<div class="example">Second</div>
</div>
Create one prototype like :
String.prototype.replaceAll = function (toReplace, replaceWith){
return this.split(toReplace).join(replaceWith);
}
and your jquery code be like :
$("div#top_container").each(function( i ) {debugger;
console.log(this.innerHTML.replaceAll('<div class="example">','*%^%').replaceAll('</div>',' ');)
});
You can use replaceWith function
$(function () {
$(".example").replaceWith(function(){
return "%^%"+$(this).text();
});
});
You can make a clone of container if you don't want to change original div.
var html="";
$(function () {
var newHtml = $("#top_container").clone();
$(newHtml).find(".example").replaceWith(function () {
html+= "%^%" + $(this).text();
});
});
console.log(html);

Extract a part of an id

I've got multiple divs with ids. I need to remove a certain part of a div ID and get it onto a variable. How can I do this? example:
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
I need to remove fruitapple1 from the id and get the remaining part assigned to a variable. The length of fruitapple1 is always the same.
You can get an array of all the IDs like this:
var collection = [];
$('[id^="fruitapple"]').each(getId);
function getId() {
var id = $(this).attr('id').split('fruitapple1').pop();
collection.push(id);
}
You can use substr for this here is how to use:-
var ids=[];
$('[id^="fruitapple"]').each(function(){
var id=$(this).attr('id');
ids.push(id.substr(11));
});
alert(JSON.stringify(ids));
Demo
The simplest way would be to replace it with an empty string
$('[id^="fruitapple"]').each(function() {
var subId = $(this).attr('id').replace('fruitapple1', '');
console.log(subId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
You can use .substring() method of javascript.
Check out this fiddle.
Here is the snippet.
var divs = document.getElementsByTagName('div');
for (i = 0; i < divs.length; i++) {
var id = divs[i].id;
alert(id.substring(11)); // length of 'fruitapple1' = 11
}
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
Try to use startwith selector,
$('[id^="fruitapple1"]').each(function() {
console.log(this.id.replace('fruitapple1', ''));
});
If you want to get it into an array variable then use map() like
console.log($('[id^="fruitapple1"]').map(function() {
return (this.id.replace('fruitapple1', ''));
}).get());
console.log($('[id^="fruitapple1"]').map(function() {
return (this.id.replace('fruitapple1', ''));
}).get());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
A simple answer using substring as suggested in my comment. I'm on mobile that's why it took long.
var idSubstring = document.getElementById("yourIdHere").id.substring(11);
alert(idSubstring);
Demo JSFiddle

jQuery .html only get last value of JSON

I have a problem with jQuery("#someID").html. It only prints the last key from the JSON.
Here is the js:
<div class="row" id="fetchmember">
<script type="text/javascript">
jQuery('#group').change(function() {
var id_group = this.value;
var memberjson = "fetchmember.php?group="+id_group;
jQuery.getJSON(memberjson, function(data) {
jQuery.each(data, function(i, items) {
jQuery("#fetchmember").html("<li>"+items.name+"</li>");
});
});
});
</script>
</div>
JSON result from one of the selected option :
[{"id":"1645819602","name":"Michael English","first_name":"Michael","last_name":"English"},
{"id":"100000251643877","name":"Bill Gaither","first_name":"Bill","last_name":"Gaither"}]
I want to print all of name from the json, but it print only last name key of the json. What's wrong with my code?
Any advice and helps would be greatly appreciated. Thank you very much
You're erasing the content on each iteration. Use append instead of html
Instead of
jQuery("#fetchmember").html("<li>"+items.name+"</li>");
Use
jQuery("#fetchmember").append("<li>"+items.name+"</li>");
At iteration, you overwrite the content with last one.
Better to use .append instead of .html, but you have to make the area empty before : jQuery("#fetchmember").empty();

Use jQuery to serialize DIV attributes and send to AJAX POST

I know serialize works with <FORM> but can it work for DIVs as well?
<div class="row" shortname="1"></div>
<div class="row" shortname="2"></div>
<div class="row" shortname="3"></div>
<div class="row" shortname="4"></div>
How can I grab all the DIV and its shortname attribute and pass everything to an AJAX post?
Like shortname=1&shortname=2&shortname=3
Thanks!
you can create an array and pass it as a JSON,
var data=new Array();
$('div.row').each(function(){
data.push($(this).attr('shortname'))
})
var jsonString=JSON.stringify(data);
No, it cannot work with divs so you'll have to create a solution. If I can assume that these divs are wrapped in a parent div, then this code will work
var queryString = '';
var x = 0;
$('#parentdiv div').each(function(){
if(x) queryString += '&';
else x = 1;
queryString += 'shortname[]=' + $(this).attr("shortname");
});
If they are not wrapped in a div, and you want to find all the divs that have the shortname attribute, change the loop to this.
$('div').find('[shortname]').each(function(){
// same stuff
});
note: I'm thinking you want the shortname to be an array. If you constuct without brackets, you may be overwriting the value of "shortname" over and over.
You can build an array with the values and pass that array as part of an object to the $.ajax data option.
var shortnames = $('[shortname]').map(function(){
return $(this).attr('shortname');
}).get();
ajax({
....
data:{shortname:shortnames},
....
});
You can do something like this...
FIDDLE
var serialized = '';
$('#serializeme div').each(function(){
serialized = serialized + 'shortname=' + $(this).attr('shortname') + '&';
});

Categories