0

when using jQuery load() to inject an HTML page into a DIV, the HTML could bring CSS files in its head, importing them in the DOM. The problem is that these injected CSS rules are then applied globally, which is not always the case I need.

Is there a way to avoid this behavior and limit the imported HTML pages CSS only within the hosting DIV?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fabio Ricci
  • 395
  • 1
  • 4
  • 16
  • 1
    Not easily, but you could maybe use an iframe instead. – Keith Nov 30 '20 at 14:39
  • 1
    probably use targeted styling. wrap your html page within a container with a particular id and update your css to target those within that container. may not be ideal for your case, but if possible, will serve the purpose. – Pirate Nov 30 '20 at 14:43
  • Thanks, but I must use a DIV :( Not easy to change requirements at this stage of the project. – Fabio Ricci Nov 30 '20 at 14:43
  • Hi Dave, thank you. What I thought was to add to each and every imported CSS rule a prefix, in my case #reader (the hosting DIV). Could it be a way in your opinion? It "smells" of regex... – Fabio Ricci Nov 30 '20 at 14:46
  • Well the not so easy option, is don't use jQuery load, but implement your own. It goes a bit like this, load the page via fetch / ajax, while still in it's XML form, extract the CSS from the Head, parse this CSS and prefix all selectors with some sort of id, do some other tricks like change the body selector too, you can then copy the stylesheets & body elements over to the current page. To be honest it's probably not that hard to do, so I'd be surprised if there wasn't lib to do this. – Keith Nov 30 '20 at 14:47
  • I don't see the problem of target being a DIV. Just create an Iframe to contain the loaded page, and insert the iframe into your DIV – netizen Nov 30 '20 at 14:50
  • @netizen I can't use iFrame. Otherwise it would have been already solved. – Fabio Ricci Nov 30 '20 at 14:51
  • This might do what your after -> https://www.npmjs.com/package//html-include-element – Keith Nov 30 '20 at 14:52
  • Why can't you use iFrames? Why do you have this restriction? – mplungjan Nov 30 '20 at 15:01

1 Answers1

0

Just get the content:

$("#myDiv").load("page.html #contentContainer")

or

$("#myDiv").load("page.html body")
mplungjan
  • 169,008
  • 28
  • 173
  • 236