Nitish Kumar
Nitish Kumar

Reputation: 6276

How to manipulate iframe objects using jquery

I've gone through lot of topics related to this question but unable to get the desired output.

I'm calling a iframe inside and html like this:

 <iframe class="full-screen-preview__frame" id="nitseditpreview" src="himu/index.php" name="preview-frame" frameborder="0" noresize="noresize" data-view="fullScreenPreview">

Suppose in this iframe I have h2 tag with a class name like this:

<body>
  <section id="about-us">
    <div class="container">
      <div class="text-center">
        <div class="col-sm-8">
          <h2 class="maincontent">
  Why with Us
  </h2>
        </div>
      </div>
    </div>
  </section>
</body>

As seen by the inspect element in browser

By using Jquery I want to manipulate this lets say for example I want to put border in this. I've tried a lot of things but I guess this thing will work if anyone fixes the bug, my jquery looks like this:

$(document).load(function () {
$('#nitseditpreview').load(function () { //The function below executes once the iframe has finished loading
    $this = $(this);
    $('#nitsmenu', this.contents()).css('border', 'solid 1px #777');
});

});

Don't know where I'm doing mistake, even I'm following same origin policy too.

Upvotes: 0

Views: 227

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21475

If both framed and framing documents are on the same domain, there shouldn't be any need for sandbox attributes or CORS hoop-jumping. But there are a number of other errors here:

  • $(document).load(...) should be $(document).ready(...) (since it has already loaded by the time your script runs)
  • you define $this = $(this), but then in the next line try to use a bare this
  • You're trying to match a #nitsmenu that doesn't appear to exist in the framed document

The following appears to work, although I'm concerned there may still be a race condition on that iframe's .load():

$(document).ready(function() {
  $('#nitseditpreview').load(function() {
      $(this).contents().find('.container').css('border', 'solid 1px #777');
  });
});

http://plnkr.co/edit/tCEHdU0ckg5q4w4tPVFU

Upvotes: 1

Related Questions