How do I select elements within a #document in CSS

2019-05-15 05:21发布

问题:

I'm trying to set the background-image of the outer <body> tag in CSS:

<html>
 <body>
  ...
   #document
    <html>
     <body>
     </body>
    </html>
  ...
 </body>
</html>

However, I can't even seem to select one of the <body> tags without affecting the other. They have no IDs, and when I try selecting via child selectors that #document complicates things (I don't even know what it is). If I try something like body html body {...}, the #document acts like a barrier that I can't get past, so it doesn't select the inner body tag.

Any ideas for how to select one of the body tags?

回答1:

The given listing appears to be a DOM inspector view. In this case, #document doesn't refer to an arbitrary element with an id of "document" — it refers to the document hosted within an <iframe> (see Node.nodeName). You can see this in Firefox's and Chrome's DOM inspectors; in fact, you can even try it right now by pointing either browser to data:text/html,<iframe>, opening the inspector and expanding the <iframe> node. IE shows the nested tree as well, but without the #document marker.

If you're seeing the background image bleed from the host document into the iframe, that means the document in the iframe doesn't have its own background.

Selectors cannot penetrate multiple/nested document trees; they are localized to the context document. This means that you cannot target elements in a document hosted within an <iframe> from within the document that contains that <iframe>. If you need to apply styles to elements in a document within an <iframe>, the CSS needs to be directly applied within that inner document, and the selectors written as though you were working with just that document.


In the somewhat less likely event that the given listing is actual source markup rather than a DOM inspector view, and #document is in fact an arbitrary element with an id of "document", then your inner <html> and <body> elements have been written off, as an HTML DOM may only contain exactly one <html> and one <body> element at a time; these would be your outer ones, not the inner ones. In that case, you could try selecting #document and applying the background to that instead, but no guarantees that it'll work correctly.



回答2:

What you are thinking about would require there to be <head></head> tags inside the #document and <iframe></iframe> tags including <link rel="stylesheet" type="text/css" href="Null.css">. If you wish to alter this via embedding and altering then you will need jQuery, but there are no guarantees with jQuery because first of all, you need to know where to put it and second of all, it may not work if multiple things use the same ids/classes on the page with the iframe and the document inside the iframe.



回答3:

Using Jquery

You can use jQuery's .content() function to access it.

$('yourIframe').contents().find('#yourItemYouWantToChange').css({
    background: 'red'
});