Crafting numerous CSS templates

I am currently working on creating multiple boxes or templates (5 on each row) from a movie API. I have successfully retrieved all the necessary data and do not require a responsive design.

https://i.sstatic.net/CNz9R.png

The issue arises when I attempt to apply my CSS class to my section "

<section id="raiz"></section>
", as it only creates a box that is then overwritten by everything within the AJAX function. Below is the code snippet:

var $movies = $.ajax({
      url: "http://api.tvmaze.com/shows",
      dataType: "json",
      method: "GET",
      cache: false,
      success: function(data) {
        console.log(data);
        for (var i = 0; i < data.length; i++) {
          //root
          var root = document.getElementById("raiz");
          //Elements
          var hyperlink = document.createElement("a");
          var img = document.createElement("img");
          var rating = document.createElement("span");
          var title = document.createElement("h2");
          var genres = document.createElement("p");
          hyperlink.href = data[i].url;
          img.src = data[i].image.medium;
          rating.innerHTML = data[i].rating.average;
          title.innerHTML = data[i].name;
          genres.innerHTML = data[i].genres;
          raiz.appendChild(title);
          raiz.appendChild(genres);
          hyperlink.appendChild(img);
          raiz.appendChild(hyperlink);
          raiz.appendChild(rating);
        }
      },
      error: function(data) {
        console.log("Error");
      }

    });
.box {
      float: left;
      height: 300px;
      width: 250px;
      background-color: lavender;
      border: solid 1px silver;
    }
<!DOCTYPE html>
<html lang="es">

<head>
  <meta charset="utf8">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
  <header></header>
  <main>
    <section id="raiz"></section>
  </main>
  <footer></footer>
  <script src="js/app.js" type="text/javascript"></script>
</body>

</html>

If anyone has suggestions on what I should do next, please let me know!

Answer №1

Your code has numerous issues that need to be addressed. First of all, you are creating your own HTML tags instead of using valid HTML elements like p or div when using the method createElement. Remember, HTML is not XML, so you can't just create any element you want. Secondly, since you are already using jQuery, there is no need to use createElement - you should utilize jQuery selectors instead. Your code is essentially invalid.

Here's a basic example of how you can use jQuery to append elements to the DOM (please note that this code is not perfect but serves as a demonstration):

$(document).ready(function() {
$.ajax({
  url: "http://api.tvmaze.com/shows",
  dataType: "json",
  method: "GET",
  cache: false,
  success: function(data) {
    for (var i = 0; i < data.length; i++) {
      var genre = data[i].genres.join(", ");
      
      $("#raiz ul").append('<li class="box"></li>');
      $("li").eq(i).append('<img src="' + data[i].image.medium + '"/>')
                    .append('<h2>' + data[i].name +'</h2>')
                    .append('<p>' + genre +'</p>')
                    .append('<p> Rating: ' + data[i].rating.average +'</p>');
    }
  },
  error: function(data) {
    console.log("Error");
  }
});
});
.box {
  display: inline-block;
  width: 45%;
  background-color: lavender;
  border: solid 1px silver;
  padding: 5px;
}

.box img {
  display: block;
  margin: auto;
  width:100%
  height: auto;
}

h2 {
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header></header>
<main>
  <section id="raiz">
    <ul>
        
    </ul>
  </section>
</main>
<footer></footer>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can anyone suggest a stellar sprite generator for me?

I am in search of a sprite generator to streamline my web development process. With so many options available, I am seeking recommendations for the best tool. Ideally, I want a generator that can produce both a sprite image and corresponding CSS files wi ...

Using Laravel and Ajax, you can implement a feature that dynamically highlights a color as either inactive or active

If you take a look at the code provided below, within my success: function (response), the getgroupstatus function will display either active or inactive based on the row column. https://i.sstatic.net/xgtu8.png function fetchgroup() { ...

Mastering the Art of Trimming with Jquery

function DisplayDataForEdit(id) { $("#editContainer").slideDown("medium"); var parentId ='item'+ id; var colIndex = 0; var $row = $("#" + parentId).parent().parent(); $row.find('td').each(f ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...

Encountering difficulty with installing sass

I recently attempted to install node-sass and, while the installation was successful, I encountered an issue where the code in main.scss was not automatically transferred to style.css. In an attempt to resolve this issue, I deleted all related files incl ...

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

Updating a database using the $json_encode() PHP Function: A Step-by-Step Guide

Looking to enhance my database using a combination of jQuery, PHP, and Ajax with json_encode and Ajax Post. However, I'm struggling with understanding how to utilize an array $json_encode to update the database with a foreach loop. How can I achieve t ...

I can't understand why this question continues to linger, I just want to remove it

Is there a valid reason for this question to persist? I'm considering removing it. ...

jQuery still not running despite using .ready

I have been attempting to run some jQuery code on my HTML page. After doing some research, I learned that using .ready may be necessary to ensure the DOM is fully loaded before executing the script. Despite this, I am still having trouble getting the scrip ...

Error message while running jQuery 3.2.1: issues with UL and LI

I have a link that displays the desired outcome Despite using jquery version 3.2.1, when I insert my code into Dreamweaver cc 2018, it fails to work. On my jsfiddle, the selection is sorted alphabetically, but on my web page it is not. var mylist = $( ...

Trigger the click() event in jQuery before the blur() event

Looking to implement autocomplete suggestions in an input field? Take a look at the code below: <input type="text" id="myinput"> <div id="myresults"></div> To hide the results' div on the input's blur event, you can use this c ...

Retrieve information and display it in a text field using ajax

Hi there, I'm having some trouble with my current code and would appreciate any help you can offer. My goal is to filter data in a search box and display the corresponding results in text boxes. I've been searching online for hours trying to find ...

Remove a Row from a Table by Clicking a Button with Ajax

I currently have an HTML table with 4 columns: SKU Group, Group_ID, Edit button, and Delete button. My focus at the moment is on implementing the delete functionality. I want it so that when the delete button is clicked, a confirmation box appears. If "OK" ...

Navigating a mobile-friendly menu anytime!

I'm in the process of creating a responsive "hamburger" menu for mobile devices. The HTML code I have implemented is as follows... .menu_closed { color: red; } .menu_open { color: blue; } <script src="https://ajax.googleapis.com/ajax/libs/jq ...

Retrieve the updated text content from a textarea using JavaScript/jQuery

For a beginner in javascript and jquery like me, I encountered an issue with a textarea element that has preset content. When I change the value on the site to "new" and click the "showme" button, the alert box displays the preset value instead of the new ...

What could be the reason for the presence of a white border in the footer section?

I am trying to create a div in the footer that sits side by side, but the current code is causing it to have an unwanted white border. <!DOCTYPE html> <html lang="en"> <head> <style type="text/css"> #botto ...

The result of the $.getJSON request is null

I have implemented a script that pulls state names from a country and populates a dropdown list with them. However, the variable j always ends up being null after the call, resulting in no options being populated in the <option> field. The URL forme ...

What's the best way to continuously increase my counter using the data received from my AJAX calls?

On the final step of my first ajax project, I have implemented a thumbs-up icon that increments a column in the database when clicked. The following code achieves this: Viewable Page HTML and jQuery: <div id="comment_id">+1</div> <div id=" ...

Codeigniter failing to perform AJAX requests

After taking some code from an example and implementing it in my controller, I encountered issues with populating another dropdown using my own table. This is what my Controller looks like: class Bkp extends CI_Controller { function __construct() { ...