Loop through classname within string of HTML using jQuery - javascript

I have a html string which is being pulled in via AJAX.
Let's say it's:
var htmlString = '<div class="post"></div><div class="post"></div>';
I'm looking for a way to loop through those posts.
Normally I would do something like:
$('.post').each(function(i, currentElement){
var htmlOfSinglePost = $(this).html();
});
The thing is I'm not sure how I can specify that it should search the htmlString, not the current DOM.
Is there a solution for this?
I'm trying to get an array of the post elements so I can pass them into the appended() method on MasonryJS, which can be seen here - http://masonry.desandro.com/methods.html#appended

You can try this : Use .filter() to get elements from htmlString
$(htmlString).filter('.post').each(function(i, currentElement){
var htmlOfSinglePost = $(this).html();
});
Demo

Related

Appending to DOM with AJAX, data displaying as string instead of HTML

I am trying to append data retrieved via an AJAX request to the DOM so I can grab it and put it into an array. However, when I append the data into the DOM it displays as a string instead of HTML. My code appending to the DOM is below, thanks!
var url = "https://xxxxxxx.com";
var $storeData = document.getElementById("data");
$.getJSON(url, function(data) {
var checkins = data.response.venues[0].stats.checkinsCount;
var formattedCheckins = Number(checkins);
$storeData.append('<p class="getData">' + formattedCheckins + '</p>')
});
I have tried this using JSON.stringify on the formattedCheckins variable as well to similar results. Thanks for your help!
Your issue is that document.getElementById is returning a native DOM Element. Using the append() method of that object places text within the element, not HTML. You seem to be confusing this with jQuery's append() method which does add HTML.
To solve this, select the #data element using jQuery instead:
var $storeData = $("#data");
var formattedCheckins = 12345;
$storeData.append('<p class="getData">' + formattedCheckins + '</p>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>
If you using jQuery, try var $storeData = $("#data"); instead.
document.getElementById returns a DOM Object.
var storeData = $('#data') returns a jQuery Object.

Delete elements in a javascript string

I have a string containing html elements, now I need to select some elements and remove them from the string.
In JQuery I tried the following:
html_string = "<ul><li data-delete>A<li><li>B</li></ul>";
html_clean_string = $(html_string).remove('[data-delete]').html();
This is what I expected:
"<ul><li>B</li></ul>"
But I got the same original string. So how can I use CSS selectors to remove html elements from a string?
You can do it like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var elems = $(html_string);
elems.find('[data-delete]').remove();
var html_clean_string = elems[0].outerHTML;
You had a couple of issues:
.remove() only operates on the elements in the jQuery object, not on child object so you have to .find() the appropriate child elements before you can remove them.
Since you want the host top level HTML too, you will need the .outerHTML.
You had mistakes in your html_string.
Working jsFiddle: http://jsfiddle.net/jfriend00/x8ra6efz/
You can also save a little jQuery with more chaining like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var html_clean_string = $(html_string).find('[data-delete]').remove().end()[0].outerHTML;
Working jsFiddle:http://jsfiddle.net/jfriend00/wmtascxf/

How to extract text from all elements of given class under given HTML element with jQuery

When I do this:
var elem = $(".region_box");
text = elem.find(".my_text").html();
I can get text from the first element deep below "elem" with class "my_text" which it finds.
But there are many elements of the class "actual_text" below elem and I want to combine the text from all of them. How would I do it?
I am new to jQuery and I searched around for solution for long time, but neither of them worked for me. Perhaps I am using this each() function incorrectly. I would very much appreciate any help.
You can use the jQuery.each
var text = '';
var elms = $(".region_box .my_text").each(function () {
text = text + $(this).text(); // use .html() if you actually want the html
});
Define a variable to hold the new string, select all of the elements you wish to extract, chain that with .each() and add the contents of the text node for that element to the variable you created to hold the new string.
(Demo)
var text = "";
$(".region_box .my_text").each(function(){ text += " " + $(this).text(); });
try something using jquery .map() method like this,
text = $('.region_box').find('.my_text').map(function() {
return $(this).text();
}).get().join(',');
As the site said, "As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array."

Can jQuery work for html strings that are not in DOM?

I have an html string that I created with a template.
This string has an html table with a bunch of rows, I'd like to manipulate this string using jquery, for example to add some classes to some rows based on logic, or other manipulation and then have jquery return a string. However, it seems that jQuery only manipulates the DOM. But I don't want to post this string into the DOM yet.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>";
//Something like
var newString = $(htmlString -> '#bla').addClass('blaClass');
// this syntax is obviously wrong, but what I mean is I'm trying
// to look inside the string not the dom
Or maybe it's better to post this string into an invisible div first and then manipulate it with jquery?
Parse it to a variable, manipulate, then append:
var origString = "<table><tr id='bla'>...";
origString = $.parseHTML(origString);
$(origString).find("tr").addClass("test");
$("body").append(origString);
Concept demo: http://jsfiddle.net/6bkUv/
Yeah, you can add a class without appending it to the dom.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>",
newString = $('<div>'+origString+'</div');
newString.find('#bla').addClass('blaClass');
console.log(newString.html());
Yes, you can definitely manipulate a string with jQuery. Here is what the following code does:
Declares a div to wrap the string in
Wraps the string in the div and does the manipulation
Finally, produces the manipulated string
No interaction with the DOM whatsoever.
var htmlString = "<table><tr id='bla'>...";
var div = $('<div/>');
div.html( htmlString ).find( '#bla' ).addClass( 'class' );
var newString = div.html();
WORKING JSFIDDLE DEMO
//OUTPUT
Original: <table><tr id='bla'><td></td></tr></table>
New: <table><tbody><tr id="bla" class="class"><td></td></tr></tbody></table>
NOTE: Please note that if your table string does not have a tbody element jQuery will include it as that makes for valid table markup.
The answers were too complicated. The answer is just a dollar sign and some parentheses:
var queryObj = $(str);
So
var str = "<table><tr>...</tr></table>"
var queryObj = $(str);
queryObj.find('tr').addClass('yoyo!');
// if you use 'find' make sure your original html string is a container
// in this case it was a 'table' container
$("body").append(queryObj);
works just fine..

Variable as jQuery selector focus

I'm using JavaScript to copy a specific div from a page into a new page. I need to remove the ID attributes for each table in the new page.
It seems that since I'm copying content from the first page, I can filter out the IDs from the string before it is written to the second page. Can jQuery take a variable as its 'focus'? Instead of manipulating the entire DOM, manipulate a particular string?
I have a non-working version of what I'm talking about:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
$("table", htmlToCopy).removeAttr('id');
currentContent.document.open();
currentContent.document.write(htmlToCopy);
currentContent.document.close();
You need to create a jQuery object by calling $(html), manipulate it, then get the HTML back by calling html().
For example:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
var newStructure = $("<div>" + htmlToCopy + "</div>");
newStructure.find("table").removeAttr('id');
currentContent.document.open();
currentContent.document.write(newElements.html());
The <div> element allows me to get its inner HTML and get the HTML you're looking for.
Who not just remove ID= as a string and forget DOM manipulation all together?
First make the string a jQuery object, then work with it:
htmlToCopy = $(htmlToCopy).find("table").removeAttr('id').end().html();

Categories

Resources