Parsing HTML from a JSON String with jQuery - javascript

I have no idea what im doing wrong, but I have a JSON string with this:
jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World</p></body></html>"});
I need to parse this to be able to modify the content. Like, for example, id want to grab the <p>'s content.
Now, in jQuery if i do:
console.log($(json.content).html());
It returns Title.
If i do:
console.log($('p',json.content));
It returns [], or, an empty array.
Finally, if I do just:
console.log($(json.content));
It returns [<title>​Title​</title>​,<p>​Hello World​</p>​]
Which is fine, but then I cant do .find() or anything. Since I wont know what the HTML will be, i cant use $(json.content)[1].
Any ideas?
==UPDATE==
After hacking at this for a couple hours i decided to try XML. My example XML was:
<?xml version=\"1.0\" encoding=\"UTF-8\"?><doc><item>One</item><item>Two</item></doc>
It was giving me the same grief, then it hit me, its a JS object, not a string and jQuery is expecting a string. I went and did
$(JSON.stringify(json.content)).find('item')
And voila! I got an array of two items. I was pretty excited but then when I went and tried it with HTML again (using the JSONP return HTML snippet above):
console.log($(JSON.stringify(json.content)).find('p'));
I still get an empty array. It's driving me mad... Any more ideas?

There might be a better way, but this works (retrieves the p elements):
$('<div />', {html: json.content}).find('p');

What is jsonp443489 here? Why not just do $.parseJSON ?
Once you have done that you should be able to access content inside it and then create a jquery object from that content and search in it.
var json = $.parseJSON(jsoncontent);
$(json.content).find('');// or you can add it to dom and search using $('#id')

Related

createContextualFragment is just spitting back the html from the string in string form

I apologize, this should be simple. I just have a string containing html that I want to append to el as "real html" and return for display.
My code, taken from other stackoverflow answers:
let fragmentFromString = function (strHTML) {
return document.createRange().createContextualFragment(strHTML);
}
let x = fragmentFromString(decodeURI("<span><B>Test</B> this</span>"));
el.appendChild(x);
BUT, all it does is append the text including the html as a child on el. It doesn't actually create the nodes and make "Test" bold, etc...
What I see in my browser is all of:
<span><B>Test<>/B> this</span>
What I WANT to see in my browser is all of:
Test this
What simple thing am I missing? Thank you.
Short answer, you use 'decodeURI' which is wrong in this case, since it's not an encoded URI.
Simply delete it, and it should work.
You should use a html string in your function.

Using variables with jQuery's replaceWith() method

Ok this one seems pretty simple (and it probably is). I am trying to use jQuery's replace with method but I don't feel like putting all of the html that will be replacing the html on the page into the method itself (its like 60 lines of HTML). So I want to put the html that will be the replacement in a variable named qOneSmall like so
var qOneSmall = qOneSmall.html('..........all the html');
but when I try this I get this error back
Uncaught SyntaxError: Unexpected token ILLEGAL
I don't see any reserved words in there..? Any help would be appreciated.
I think the solution is to only grab the element on the page you're interested in. You say you have like 60 lines. If you know exactly what you want to replace..place just that text in a div with an id='mySpecialText'. Then use jQuery to find and replace just that.
var replacementText = "....all the HTML";
$("#mySpecialText").text(replacementText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mySpecialText">Foo</div>
If you're only looking to replace text then jaj.laney's .text() approach can be used. However, that will not render the string as HTML.
The reason the way you're using .html() is likely illegal is that qSmallOne is not a JQuery object. The method cannot be performed on arbitrary variables. You can set the HTML string to a variable and pass that string to the .html() function like this:
var htmlstring = '<em>emphasis</em> and <strong>strong</strong>';
$('#target').html(htmlstring);
To see the difference between using .html() and .text() you can check out this short fiddle.
Edit after seeing the HTML
So there is a lot going on here. I'm just going to group these things into a list of issues
The HTML Strings
So I actually learned something here. Using the carriage return and tab keys in the HTML string is breaking the string. The illegal-ness is coming from the fact the string is never properly terminated since it thinks it ends at the first line. Strip out the white space in your strings and they're perfectly valid.
Variable Names
Minor thing, you've got a typo in qSmallOne. Be sure to check your spelling especially when working with these giant variables. A little diligence up front will save a bunch of headache later.
Selecting the Right Target
Your targets for the change in content are IDs that are in the strings in your variables and not in the actual DOM. While it looks like you're handling this, I found it rather confusing. I would use one containing element with a static ID and target that instead (that way you don't have to remember why you're handling multiple IDs for one container in the future).
Using replaceWith() and html()
.replaceWith() is used to replace an element with something else. This includes the element that is being targeted, so you need to be very aware of what you're wanting to replace. .html() may be a better way to go since it replaces the content within the target, not including the target itself.
I've made these updates and forked your fiddle here.

XML to HTML function for Refreshing Information

I am making a real time train board that pulls XML data from a website, populates it and animates it in. I have laid it out and got the animation set, but now I need help getting the XML data in the right spots.
Codepen of the animation: http://codepen.io/Spiderian/pen/FBjhk
The XML I'm trying to populate and recheck it every so often.
<trains>
<line><name>2</name><status>GOOD</status><text/><Date/><Time/></line>
<line><name>3</name><status>DELAYS</status><text/><Date/><Time/></line>
<line><name>4</name><status>WORK</status><text/><Date/><Time/></line>
<line><name>5</name><status>GOOD</status><text/><Date/><Time/></line>
</trains>
Will I have to use something different for the .append function to get it to work with the XML?
jQuery will work fine with XML, too. I will focus on the parsing of it in this answer, since I assume you're already familiar with fetching the XML from whatever web service you use with AJAX.
Create a new jQuery object with the XML, and then use the typical selectors to parse it. For example, to get the service on the first line, you can use the following:
var stats = xml.find('line:first status').text();
Here's how you can create a new jQuery object from XML:
var xml = $('<trains>\
<line><name>2</name><status>GOOD</status><text/><Date/><Time/></line>\
<line><name>3</name><status>DELAYS</status><text/><Date/><Time/></line>\
<line><name>4</name><status>WORK</status><text/><Date/><Time/></line>\
<line><name>5</name><status>GOOD</status><text/><Date/><Time/></line>\
</trains>');
Once you have the value from the XML, you can use either text() or html() to add it to your existing markup.
jsFiddle Demo

Outputting String to HTML using javaScript

there have been many questions like this before, but the answer usually involved referencing the element to be outputted to within the script. in my case, elements are created dynamically on load (it's hosted on Tumblr, to be specific), so there's no referable ID for each of the elements I need to output a string to.
is it possible to do this? jQuery can be used if it makes things much simpler. my function takes a string as an input and outputs a string using return.
$('.post .posttext a').html(YourfunctionThatReturnsAString());
This should do it
$('.post .posttext a') -> this returns an array of a elements.
$('.post').eq(the post number).find('.posttext a') -> replace "the post number" with the number of your post if you want to target something more specific.
You can then call the text("your text") method to set the text.

Weird Behaviour in jQuery's html method

Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?
Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.
jQuery only accepts a string as an argument for the val parameter of the html() method. If you pass a number like you are it will call the html() method override that sets the contents of the element but the value of the argument will end up being null or an empty string.
Try this:
$("p").html((0).toString())
Relevant documentation
I guess that at some point, it checks if (newContent == false), and doesn't continue with adding any content? I tried looking at the source, but got a bit lost...
I also guess that this would not be counted as a bug, since the function calls for a string, and if "0" is passed (as a string), it works as expected.
A workaround would be to do this:
var myNum = 0;
$('p').html('' + myNum);
The code performing the html call was within someone else's plugin and rather than modify it, making upgrading it tedious, I just wrote the following tiny plugin that modifies the html method to do as spoon16 recommended.
(function($) {
var oldHtml = $.fn.html;
$.fn.html = function (content) {
oldHtml.apply(this, [content.toString()]);
}
})(jQuery);
It's a little bit of a hack, but it's working for me and doesn't require me to modify the Plugin I'm using.
I just thought someone else might like to see this.
Try using text() instead html().
I geuss you missed part of how jQuery works,
$('p')
returns all paragraphs and the html( val ) function:
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
http://docs.jquery.com/Attributes/html#val
So if you just want to set the contents for the first p use
$("P").eq(0).html( 'something' );
or to get the html:
$("P").eq(0).html();
http://docs.jquery.com/Core/eq#position
more on jQuery selectors here:
http://docs.jquery.com/Selectors

Categories

Resources