AnimaVivens
AnimaVivens

Reputation: 409

Javascript how to access elements from am HTML file loaded with jQuery

I am interested how to access HTML elements from an "outside HTML file" that is embedded into the "core HTML file" (the embedding was done using jQuery) by using javascript (which is part of the "core HTML file").

jsfiddle: https://jsfiddle.net/King_Fish/bfzqjw38/5/

Let me provide my example: I have a page saved as PlantCard.html (this is the "outside HTML file). Then, in Main.html (the "core HTML file") I have created 4 divs and loaded the PlantCard.html into them using javascript. This embedding was done in the following manner:

var plantCardIds = ["#test", "#test1", "#test2"];

$(document).ready(function() {
 loadPlantCards();
});

function loadPlantCards() {
  var plantInfo = plantCardsInfoLoader();

  var i;
  for(i = 0; i < plantInfo.length; i++) {
    $(plantCardIds[i]).load("PlantCard.html");

    /*I want to access and change the elements of "PlantCard.html" HERE!*/
  }
}

The function loadPlantCards() loads all of the "plant cards" (containers with information about specific plants) by iterating through the plantCardIds array (contains the ids of the divs into which the PlantCard.html should be loaded into.

However, I want each "plant card" to display different types of information and also a different image of the plant. Therefore, I have to access the elements inside PlantCard.html, and here is the problem. So far, I have tried to achieve the desired effect in this manner:

function loadPlantCards() {
  console.log("Loading plants...");

  var plantInfo = plantCardsInfoLoader();

  var i;
  for(i = 0; i < plantInfo.length; i++) {
    $(plantCardIds[i]).load("PlantCard.html");   
$(plantCardIds[i]).getElementById("plant_name").innerHTML=plantInfo[i].plantName;
  }
}

However, when using this line of code ($(plantCardIds[i]).getElementById("plant_name").innerHTML=plantInfo[i].plantName;) to access the html inside the respective div which should hold the "plant card", I am greeted with this exception:

Uncaught TypeError: $(...).getElementById is not a function

Now I would be really glad if someone explained how to access the HTML elements from a page, which is embedded inside a div.

Upvotes: 0

Views: 67

Answers (1)

Justin Hendrickson
Justin Hendrickson

Reputation: 101

.getElementById is great for this purpose in Vanilla JavaScript, but is not a method in JQuery. To get an element from an HTML file, you should instead run:

$(plantCardIds[i]).find('#plant_name')

That should work.

Upvotes: 1

Related Questions