Ben Cavenagh
Ben Cavenagh

Reputation: 748

Adding HTML to iFrame using jQuery and finding class

I am trying to add some text into an iframe in my code but for some reason I can't get the jquery to find a specific class in the frame. if I use a generic element like 'body' it works but I need to be able to reach the class '.shopify-buy__product__actual-price'.

This code works:

jQuery(document).ready(function( $ ){
    var iframeDOM = $('iframe').contents();
    var node = iframeDOM.find('body').html('<p>Starting at</p>');
});

But this does not:

jQuery(document).ready(function( $ ){
    var iframeDOM = $('iframe').contents();
    var node = iframeDOM.find('.shopify-buy__product__actual-price').html('<p>Starting at</p>');
});

Can someone explain how I can reach that class?

here is the full iframe code: enter image description here

Upvotes: 0

Views: 193

Answers (2)

user9988919
user9988919

Reputation:

You could try this:

$(function() { 
  var iframe = $("iframe");
  iframe.on( "load", function() {
    var frame = document.getElementById("iframe");
    var newElement = frame.contentWindow.document.getElementsByClassName("index__sub-menu___3XMYU")
    var text = document.createTextNode("Starting price");
    newElement[0].appendChild(text)

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

You need to let the iframe load before accessing elements

Try

jQuery(document).ready(function($) {
  $('iframe').on('load', function() {
    $(this).contents().find('.shopify-buy__product__actual-price').html('<p>Starting at</p>');
  });
});

Upvotes: 1

Related Questions