0

I'm creating elements with jQuery and then appending them to existing HTML. Here is my jQuery code:

var h1 = $(data2).find("h1").html();
var image = $(data2).find(".tutorialContent .wsite-image:first-child").html();
$(".searchResults").append('<a class="searchResultsImageTitle">' + '<div class="searchResultsImage">' + image + '</div>' + '<div class="searchResultsTitle">' + h1 + '</div>' + '</a>');});

I want the code above to produce this HTML:

<a class="searchResultsImageTitle">
  <div class="searchResultsImage"></div>
  <div class="searchResultsTitle"></div>
</a>

But instead I get this HTML:

<a class="searchResultsImageTitle"></a>
<div class="searchResultsImage"></div>
<div class="searchResultsTitle"></div>
Weebs
  • 155
  • 2
  • 10
  • did you try to have `` tags instead of `
    `, your code will output invalid HTML, maybe replacing the `
    ` with `` would work for you. checkout this [is-putting-a-div-inside-an-anchor-ever-correct](https://stackoverflow.com/questions/1827965/is-putting-a-div-inside-an-anchor-ever-correct)
    – ROOT May 01 '20 at 11:31
  • 2
    When removing the }); at the end of your append(), it works: https://jsfiddle.net/32nbp08k/ – matthias_h May 01 '20 at 11:35

4 Answers4

0

Your code have error syntax, refined it, the code the a tag still wrap 2 div inside as

<a class="searchResultsImageTitle">
  <div class="searchResultsImage"></div>
  <div class="searchResultsTitle"></div>
</a>

$(".searchResults").append('<a class="searchResultsImageTitle" href="#">' + '<div class="searchResultsImage">' + 'image' + '</div>' + '<div class="searchResultsTitle">' + 'h1' + '</div>' + '</a>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="searchResults"></div>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • With the addition of the apostrophes around the variables, the variables are now invalid. Sorry, I should have included the variables from the start. – Weebs May 01 '20 at 11:41
0

I broke it up just a bit but this should do the trick

const $a = $('<a class="searchResultsImageTitle">');
const $d1 = $('<div class="searchResultsImage">');
const $d2 = $('<div class="searchResultsTitle">');

$a.append($d1);
$a.append($d2);
$(".searchResults").append($a);
0

When removing the }); at the end of your append(), it works:

let image = "<img src='https://dummyimage.com/100x100/000/fff'/>";
let h1 = "<h1>Title</h1>";
$(".searchResults").append('<a class="searchResultsImageTitle">' + '<div class="searchResultsImage">' + image + '</div>' + '<div class="searchResultsTitle">' + h1 + '</div>' + '</a>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="searchResults">
</div>
matthias_h
  • 11,356
  • 9
  • 22
  • 40
0

I appreciate everyone's answers! I discovered the problem to be a conflict between the jQuery code and the HTML one of the variables was pulling. Thank you all!

Weebs
  • 155
  • 2
  • 10