Steven Krol
Steven Krol

Reputation: 27

Change content after being loaded by Jquery

I'd like to change the style of a certain element after loading. However it gives me a null pointer.

function loadFriends() {
    $("#friendsContainer").load("friends.html");
}

selectCurrentSetting();

function selectCurrentSetting() {
    console.info("test");
    var selection = document.getElementById("friendsContainer").getAttribute("selection");
    console.info(selection);
    if (selection != null) {
        document.getElementById(selection).classList.add("selected");
    }
}

this is what it load in friends.html

<div id="friends" class="container friends_container">
    <div class="container_content" id="container_content">
        <div class="option" id="#profile" onclick="">Profile <span class="fas fa-cog icon"></span></div>
        <div class="option" id="#settings" onclick="">Settings <span class="fas fa-cog icon"></span></div>
        </div>
    </div>
</div>

and this is what it should replace

<div id="friendsContainer" selection="settings"></div>

The code selectCurrentSetting() should change the style of #settings in friends.html after it gets loaded in. However it gets me a null pointer. error I get in console

How would I get it to execute the code in selectCurrentSetting() after the elements needed are available?

Upvotes: 1

Views: 353

Answers (2)

Vega
Vega

Reputation: 28738

Remove # in

id="#settings"

or set

selection="#settings"

as you don't need # in your markup to set the id

Working demo

Upvotes: 1

Nishant Dixit
Nishant Dixit

Reputation: 5522

Try this :)

   function loadFriends() {
      $("#friendsContainer").load("friends.html", function(responseTxt, statusTxt, xhr) {
          if (statusTxt == "success")
              selectCurrentSetting();
          if (statusTxt == "error")
              console.log("Error: " + xhr.status + ": " + xhr.statusText);
      });
  }

Upvotes: 0

Related Questions