8

Hi friends I have tried to add class for iframe html elements using jquery but I can't, I dont know how. could you explain how can this be possibly done. I tried to add class for iframe using query

$("iframe").addClass("myClass");

it worked for iframe but I want to add the class inside the iframe elements in jquery could you help me in this to solve it.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Sri
  • 631
  • 2
  • 7
  • 21

5 Answers5

5

You need to use the function contents() to get the document inside the iframe, and then you have to use the function find() to select the element inside the iframe.

$("iframe").contents().find("#element").addClass("myClass");
Khalid
  • 4,730
  • 5
  • 27
  • 50
  • I tried this but It didn't work could you explain this in the iframe elements can we put iframe id and in the find the element can we put class name ? – Sri Aug 15 '14 at 11:22
  • jQuery("#ssf_M00zMjM0NkzSNTQ2ttQ1STFO0k1MMwGyjI2SjC0MDcyNDI0A").contents().find("#35656").addClass("test"); can we add like this it will work or not? – Sri Aug 15 '14 at 11:25
  • yes if our iframe's id is `ssf_M00zMjM0NkzSNTQ2ttQ1STFO0k1MMwGyjI2SjC0MDcyNDI0A` and the id of the element inside the iframe is `35656` – Khalid Aug 15 '14 at 11:27
  • its not working for me dont know why its causing but it showing error like this Blocked a frame with origin "http://192.168.1.116" from accessing a frame with origin "http://app-siwiw8.sharpspring.com". Protocols, domains, and ports must match. not show any errors in the console – Sri Aug 15 '14 at 11:32
  • 1
    it because cross-origin access is denied. if you own the page inside the iframe you can solve this problem, otherwise you cant, read this http://en.wikipedia.org/wiki/Same_origin_policy – Khalid Aug 15 '14 at 11:37
2

This solution is working well. First you need to create javascript function like this

function addingClass()
{
    $("#iframe").contents().find("#element").addClass("myClass");
}

Then on your iframe control just add onload="addingClass();"

Hope this help.

Rosidin Bima
  • 227
  • 3
  • 5
1

Check jQuery/JavaScript: accessing contents of an iframe

$("iframe").contents() gives access to the html-elements inside the iframe.

Community
  • 1
  • 1
Johan
  • 3,202
  • 1
  • 23
  • 19
1

Try This:

$("iframe").contents().find('YourElemnet').addClass('myClass')

See for more Info : contents

Ritesh Chandora
  • 8,382
  • 5
  • 21
  • 38
  • could you explain this in the iframe elements can we put iframe id and in the find the element can we put class name ? – Sri Aug 15 '14 at 11:20
1
  1. First get the iframe with JS. StackOverFlow

  2. Add the CSS file to the iframe StackOverFlow.

Then you can use all the CSS you want. :)

Caveman
  • 2,527
  • 1
  • 17
  • 18