jquery: unable to find elements from jQuery object - javascript

I am fetching HTML string and I want to construct a jQuery object from it and then perform operations but I am getting undefined.
var data = '<h1>Hi World</h1';
var html = '<div id="rendered">'+data+'</div>';
//var content = $($.parseHTML(html));
var content = $.parseHTML(html);
console.log($(content).find('#rendered').html()) // it says undefined

find() is used to look for child elements. #rendered is the parent node in the HTML structure you create, so find() doesn't return anything. You need to use filter() instead as that includes the current node when searching.
Also note that $.parseHTML() isn't required - jQuery does this automatically when you provide a HTML-formatted string to the jQuery object contructor.
var data = '<h1>Hi World</h1';
var html = '<div id="rendered">' + data + '</div>';
console.log($(html).filter('#rendered').html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

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/

Loop through classname within string of HTML using jQuery

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

Convert htmlString to Dom object in Javascript

I made a http request and received a htmlString, now I want to convert it to Dom object to query its elements.
Thanks for you help
You can create a container object (I've used a div here) and then assign your html string to .innerHTML and then you can query the child objects that are created.
var container = document.createElement("div");
container.innerHTML = htmlString;
The child nodes of the container object are what is created from your HTML.
using jQuery you could do something like this:
var yourStringFromServer = '<div><div id="helloWrap"></div></div>';
var a = $(yourStringFromServer); // create new jQuery instance with string
a.find('#helloWrap').html('hello'); // find the helloWrap node and set html
a.appendTo('body'); // append html to body

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