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

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.

Related

jquery: unable to find elements from jQuery object

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>

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."

Trying to replace a html attribute using a click function

I'm trying to take an a element and take the information from the data-id attribute and store it into a variable. I want to then splice this variable so I get the part that I need and implement it into another variable with some text. From that I then want to replace the src attribute of an iframe with the variable. Unfortunately, this doesn't seem to be working at all and I can't find the issue.
Here is the code:
$('.watchvideo').click(function(){
var idu = $(this).attr('data-id');
var id = "//www.youtube.com/embed/"idu.substr(27,37);
$('.videofeatem').setAttribute("src", id);
});
You have 2 issues in code:
1) concatenating substring
2) setting attribute via jquery
var id = "//www.youtube.com/embed/"+idu.substr(27,37);
$('.videofeatem').attr("src", id);
Without seeing the HTML, it's tough to be sure, but a + fixes the obvious problem:
$('.watchvideo').click(function(){
var idu = $(this).data('id');
var id = "//www.youtube.com/embed/" + idu.substr(27,37);
$('.videofeatem').attr("src", id);
});
Also, note that data-xxx attributes can be read by jQuery as .data('xxx')
Simply.
var id = "//www.youtube.com/embed/" + idu.substr(27,37);
Since you're using jQuery, use the .attr() method instead of the .setAttribute().

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

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