简体   繁体   中英

Changing the innerHTML of an HTML object with javascript

I am loading an external page into an HTML object:

var object = document.createElement('object')
object.data = 'myPage.html'
$("#myDiv").html(object)

Now I want to modify the source of object . But I can't figure out how to use jQuery to access any of the elements of myPage.html . For example:

$("#myPageDiv").css('background-color', '#000');

has no effect. How can I modify the elements within the injected HTML object?

The innerHTML of an object is fallback content .

It is to be displayed if the external resource the object is loading isn't supported.

Assigning an HTML document's URL to data is effectively using the object as an <iframe> . You should probably use an iframe instead as they have been consistently supported among browsers for much longer.

Once you recognise you are dealing with a frame, you can find plenty of information on how to access the content.

You ask " how to use jQuery to access any of the elements of myPage.html"

 var object = document.createElement('object') object.d = '<div id="x">XXX</div>' $("#my").html(object.d); $('#x').text("<b>Some</b> new text.");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="my">ddd</div>

Try this

var object = document.createElement('object')
object.d = '<div id="x">XXX</div>'
$("#my").html(object.d);
$('#x').text("<b>Some</b> new text.");

The Jquery's load method and css method should be able to do the trick.

Hence, please try this (for demonstration purpose):

HTML (eg main.html )

  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>

<input type=button onclick="javascript:step1();" value="(Step 1) Load HTML">

<div id=myDiv></div>


<input type=button onclick="javascript:step2();" value="(Step 2) Change color">


<script>

function step1()
{
$("#myDiv").load('myPage.html');
}

function step2()
{
$("#myPageDiv").css('background-color', '#000');

}

</script>

and for the myPage.html

This is a test
<br>
<div id=myPageDiv>NEED TO CHANGE BACKGROUND COLOR</div>

You may see a fully working HTML here:

http://www.createchhk.com/so_Jan05.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM