0

I'm new to JavaScript and jQuery. So far, I could google all of my problems but with the following issue I need help.

To keep the index.html small to read I inject certain div containers having given IDs with external stored HTML files using the jQuery load function (I cannot do it with a server side language like PHP as the CMS I am using does not allow to use <?php><?> tags. So I am stuck with client side solutions.).

This works fine :-). However, I need to change some CSS attributes after loading. However, the content dynamically loaded with jQuery cannot be touched with jQuery.

Here is a demo code of what I try to achieve:

My index.html I am calling:

<html>
<head>
    <title>Injection Test</title>
    <style>
        .textformat {
            text-align: left;
        }
    </style>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

    <script>
        $(function () {
            $("#includeHere").load("tobeincluded.html");

            $(".textformat").css("text-align", "center");
        });
    </script>
</head>
<body>
<div id="includeHere"></div>
<div class="textformat">Bye</div>
</body>
</html>

The tobeincluded.html I am injecting:

<div class="textformat">Hi</div>

I would expect that "Hi" is centered, too. But only "Bye" is centered as it is available in the DOM right from the beginning.

How do I make "Hi" centered?

Thanks a lot!

1 Answer 1

1

I think you have to wait until load has completed, so apply the css in the callback of the .load() method

$("#includeHere").load("tobeincluded.html", function() {
  $(".textformat").css("text-align", "center");
});
Sign up to request clarification or add additional context in comments.

2 Comments

That's it!!! JS Callbacks have been new to me. Learnt something new today :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.