clean up html element coming from other source - javascript

When I console.log(data) from my ajax callback, it returns the entire html file which includes scripts, css etc which breaks my page. How can I get only the element block which I need? I only need the data within .container.

I think easiest way is to use jquery load function. There is possibility to take only fragment of loaded page.
http://api.jquery.com/load/

I would do this using regular expressions.
For example, if you wanted to get the content of all .container elements, you could try this regexp:
<[^>]+class="container"[^>]*>([^<]+)<\/[^>]+>
and then collect the captured groups.
See working example on Regex101.com.

Easiest way would be append in hidden tag. Then search for using $(".container")
it will return the whole div and you can get html .
Here is script code that can help you
(use jquery library)
var b= $(".container");
console.log(b[0].outerHTML);
PLEASE CHECK THIS BELOW FIDDLE
http://jsfiddle.net/oyvv9nL0/

Related

how to avoid fetching a part of html page which is being called inside another page?

I am calling a .html page(say A.html, which is dynamically created by another software each time a request is made) inside another webpage (say B.html). I am doing this by using the .load() function. Everything works fine but the problem is I donot want the so many "br" tags (empty tags) present at the end of A.html into B.html. Is there any way to avoid fetching those "br" tags into B.html? Any suggestion would be of great help. Thank you in advance.
You can't avoid loading part of a file when you are just accessing it.
The best option would be to simply remove the extra <br> tags from the document to begin with. There is probably a better way to accomplish whatever they are attempting to accomplish.
With some server-side scripting, it could be possible to strip them automatically when you load it, but would probably be pretty bothersome to do.
Instead, if you can't remove the <br> elements for some reason, what might be easier, if you are just dealing with a handful of <br> tags would be to simply strip them out.
Since you mention using the load() function, I'm guessing you are using jQuery.
If that's the case, something like this would cleanly strip out any extra <br> tags from the end of the document.
Here is a JSfiddle which will do it: http://jsfiddle.net/dMJ2F/
var html = "<p>A</p><br><p>B</p><br><p>C</p><br><br /><br/>";
var $html = $('<div>').append(html);
var $br;
while (($br = $html.find('br:last-child')).length > 0) {
$br.remove();
}
$('p').text($html.html());
Basically, throw the loaded stuff in to a div (in memory), then loop through and remove each <br> at the end until there aren't any. You could use regex to do this as well, but it runs a few risks that this jQuery method doesn't.
You shout delete the br-tags in your A.html.
Substitute them by changing the class .sequence with marging-top:30px
And have an other value in your B.html-file.
You also can run this:
$('br', '.sequence').remove();​
in the load-function. It will strip all br-tags.
You can't avoid fetching a part of your page, but you CAN fetch only a part of it.
According to the jQuery docs, you can call load like this:
$("#result").load("urlorpage #form-id");
That way, you only load the form html inside the result element.

Are HTML allowed inside HTML attributes?

For example, lets say you have something like this:
<div data-object="{'str': '<h1>This is a nice headline</h1>'}"></div>
Is this allowed in HTML5 and will it render properly in all browsers?
Edit:
With properly I mean that the browser will ignore and NOT render the H1 in any way ;)
Yes, it's allowed as long as it's quoted correctly.
Will it render? The H1 element? No - because it's not an element, it's just a bit of text inside an attribute of the div element.
Yes, browsers won't render any HTML tags inside attributes. This is pretty much common when you want to move the element later so it would show up. The only problem is that this is not a way to go as this does not create an element in DOM, thus, it will be much slower.
Try to find a way or ask for an alternative/better way to reuse the element which is hidden when the page is loaded.
Yes it's allowed and possible, but to make it work you have to make it valid JSON by using double quotes:
<div data-object='{"str": "<h1>This is a nice headline</h1>"}'></div>
Now to parse it just have: (jQuery will parse it to JSON all by itself)
var element = $("div").eq(0);
var rawData = element.data("object");
var rawHTML = rawData["str"];
$(rawHTML).appendTo("body");
Live test case.

Replace a set of html br elements with another in jQuery -- parsing HTML with jQuery

So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.
Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.
So ultimately, what I need to do is come up with a jQuery statement that replaces
<br><br clear=all><br>
with
<br />
I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?
Thanks in advance for any help!
Use the Next Adjacent Selector (+):
$("br+br").remove(); //Removes all <br> tags in front of another
jsFiddle demo
Assuming they are in the exact format you gave, you can do this:
var br = $('br[clear="all"]');
br.attr('clear', '');
br.prev('br').remove();
br.next('br').remove();
You can play with selector attributes, not inside the onload but inside the jquery ready (http://api.jquery.com/ready/)
$('br[clear=all]').remove();
more details on selector attribute:http://api.jquery.com/attribute-equals-selector/
Why donn`t just replace the html of the RSS HTML container:
yourContainerElem.innerHTML = yourContainerElem.innerHTML.replace(/<br><br clear=all><br>/gi, '<br />');
To remove all but one:
$('br,[clear!="all"]').remove()
Then to remove the 'clear=all':
$('br').removeAttribute('clear')
You better do this with regexps not with jquery. Simplest example:
string.replace('<br><br clear=all><br>', '<br />')

Fetching HTML into a <div> and overwrite content

I have a website with a top panel and a body part. The top panel can be toggled between hidden and shown.
The body part should contain the actual content of the website.
As I don't want to hard-code every single site, I would like to stay with the panel and only reload the content.
This seems to can be done using AHAH and this tutorial.
The problem is that, if new content is loaded, it just pushes the old content down.
My question is, how can I overwrite the old content with the new, fetched content?
Thanks a lot in advance for the help!
Use:
document.getElementById('yourDivID').innerHTML = theHTML;
However any JavaScript in theHTML will not be evaluated.
The prototype.js library has a good function, Ajax.Updater(), to do this sort of thing, and it is less limited than the ahah.js lib, it sounds (can harvest a chunk of any page, local or remote, unlike AHAH). Like jquery, there is a special $() function to get at stuff, use that to prune before appending.
$( 'target_div_id').childElements().each( function( child) { child.remove(); } )
Ajax.Updater( 'target_div_id', 'related_page.html')
Trailing options can be added to refine how much of the downloaded "page" is used.
Ajax.Updater
Element
If you're using jQuery:
$("#divid").html("some html value goes here");
Jquery would be the best way, here is a link to that page;
http://docs.jquery.com/Attributes/html#val

Using jQuery, how do I change the elements html value? (div)

Using a ajax request I want to change content of my div.
<div id="d1">202</div>
So I want to change the content to a different number.
$('d1').InnerText???
Also, say I wanted to increment the number, how could I do that? Do I have to convert to int?
$("#di").html('My New Text');
Check out the jQuery documentation.
If you wanted to increment the number, you would do
var theint = parseInt($("#di").html(),10)
theint++;
$("#di").html(theint);
P.S. Not sure if it was a typo or not, but you need to include the # in your selector to let jQuery know you are looking for an element with an ID of di. Maybe if you come from prototype you do not expect this, just letting you know.
This would changed the inner text of your HTML element.
$('#d1').text(parseInt(requestResponse)++);
Unless you're embedding html like <b>blah</b> I'd suggest using $("#di").text() as it'll automatically escape things like <, > and &, whereas .html() will not.
Use the text function:
$("#d1").text($("#d1").text() + 1);
$('#d1').html("Html here");
jQuery('#d1').html("Hello World");
if your value is a pure text (like 'test') you could use the text() method as well. like this:
$('#d1').text('test'); Or $('#d1').html('test');
anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:
$(document).ready(
function() {
$('#d1').text('test');
}
);
this way the script executes after the HTML of the div is parsed by the browser.
$("#div1").innerHTML="your text goes here..";

Categories

Resources