Search code examples
jqueryiframeaddclasstoggleclass

toggle class to HTML within an iframe


I'm developing a site where I want to toggle a class on the html element within an iframe on that page. I'm currently doing this

if ($('html').hasClass('flexbox')) {
  $('#flexbox').click(function () {
    $("html").toggleClass('flexbox').toggleClass('no-flexbox');
  });
}

which works on the documents HTML but I need to target the iframe id="myiframe" (for example)

if ($('#myiframe html').hasClass('flexbox')) {
  $('#flexbox').click(function () {
    $("#myiframe html").toggleClass('flexbox').toggleClass('no-flexbox');
  });
}

doesn't work. Any ideas using contentWindow or similar would be gratefully received.

update: the domain in the iframe will be different.


Solution

  • use contents(). try this

     if ($("#myiframe").contents().find("html").hasClass('flexbox')) {
       .....
    

    note: make sure the iframe is in the same domain..

    if it is in different domain then it is not possbile.. the same origin policy will restirct it to do so...