'Appending content of a variable to a div with appendTo()

Hi I'm working on a project where I have a multi-image slider. Each image needs to have a legend.

I'm getting the alt tag from the image and storing it in a p tag with a legend of legend--text.

I've then created a function that plays when I change slides. This is where I'm having a problem.

I'm setting a variable that gets the active slide, and another one that gets the legend from the active slide - this works fine. I then tried to use the appendTo() function to copy the content from the legend variable to a div tag with a class of .project__information.

I understand that this is not working because it's not a DOM element, but I've looked for solutions and can't really find any.

Here's my code:

// For each active slide get the alt attribute and store it in <p>
$('.is--legend').each(function() {
  var $this = $(this);
  $this.append('<p class="legend--text">' + $this.parent().find('img').attr('alt') + '</p>');
});

// Set splide slider
var elms = document.getElementsByClassName('splide');
for (var i = 0, len = elms.length; i < len; i++) {
  var splide = new Splide(elms[i], {
    type: 'loop',
    drag: 'free',
    focus: 'center',
    perPage: 3,
    autoWidth: 'true',
    breakpoints: {
      767: {
        perPage: 1,
      }
    }
  }).mount();
}

function slideChange() {
  // Gets active slide
  var activeSlide = $(".splide__slide.is-active:not(.splide__slide--clone)");
  console.log('Passing through the', activeSlide);
  // Gets the legend
  var myLegend = activeSlide.find('.legend--text').text();
  console.log('Getting the new', myLegend);
  myLegend.appendTo('.project__information');

}

splide.on("move", function() {
  slideChange();
});
slideChange();

If anyone has an idea as to how I could achieve this, some related documentation about how to proceed, please let me know



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source