简体   繁体   中英

Target the body of html loaded into div

I am loading html pages into a div using jQuery. How can I target the body of the html pages to apply margin using jquery/css? I can do it manually on each html page but I was looking for a quicker way.

My attempt(which isn't working):

$myDiv= $targetDiv.find("#targetContent");
$myDiv.load($(this).attr('href'));
$myDiv.find("body").css("margin-top","50px");

link:

You cannot have the body inside of a div. body is the parent of all elements in the html page. You might want .parent()

$myDiv.parent("body").css("margin-top","50px");

There could be only one body element in the whole document. However you can use iframe 's.

$myDiv = $targetDiv.find("#targetContent"); //assuming that #targetContent is an iframe
$myDiv.attr('src', $(this).attr('href'));
$($myDiv.get(0).contentWindow.document.body).css("margin-top","50px");

Remember that you can access iframe's content only if its src is from the same domain.

EDIT :

I figured out that jQuery.load function trims the body and head tags from the loaded HTML so changing body margin gives you nothing. All you have to do is expand padding of the container element

$myDiv= $targetDiv.find("#targetContent");
$myDiv.load($(this).attr('href'), function() {
    $myDiv.css("padding-top","+=50px");
});

EDIT 2 :

If you want to access the first div loaded by jQuery you have to do

$myDiv.children('div').first().css("padding-top","+=50px");

But if you want the solution more close to your question you can add another div in your #targetContent and add the padding to it. I assume that #targetContent contains some more elements. The above approach should resolve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM