John
John

Reputation: 65

How to convert a JavaScript function into a jQuery one?

I have this JavaScript function and I want to have the same but in jQuery but it's not working correctly, the list items are not appearing:

function showList(section, books) {
  let olBooks = document.createElement("ol");
  let liBook = null;

  for (let book of books) {
    liBook = document.createElement("li");
    liBook.id = value.id;
    liBook.classList.add(CLASS_BOOK);
    liBook.innerHTML = "<p>" + booksInHTML(book) + "</p>";
    olBooks.appendChild(liBook);
  }
  section.append(olBooks);
}

With jQuery is not working:

function showList(section, books) {
   var olBooks = $("<ol/>");

    $.each( books, function( index, value ) {
     var liBook =  $("<li/>");

     liBook.id = value.id;
     liBook.classList.add(CLASS_BOOK);
     liBook.text("<p>" + bookInHTML(value) + "</p>");
    olBooks.append(liBook);
  });
  section.append(olBooks);
}

Upvotes: 0

Views: 42

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371203

To set the id property with jQuery, you need to use .prop (or, less desirably, .attr):

liBook.prop('id', value.id);

Also, to set the class of an element with jQuery, use addClass:

liBook.addClass('CLASS_BOOK');

Also, to set the HTML of an element with jQuery, use the .html method. If you use the .text method, the result will set the text content of the element, not the HTML:

liBook.html("<p>" + bookInHTML(value) + "</p>");

But concatenating HTML strings from possibly untrustworthy user input can allow for arbitrary code execution, which is a security risk - it's also inelegant. Consider selecting the <p> first, and setting its .text:

$("<li><p></p></li>")
  .appendTo(liBook)
  .prop('id', value.id)
  .addClass(CLASS_BOOK)
  .find('p')
  .text(bookInHTML(value));

Live demo:

function showList(section, books) {
  var olBooks = $("<ol/>").appendTo(section);
  $.each(books, function(index, value) {
    $("<li><p></p></li>")
      .appendTo(olBooks)
      .prop('id', value.id)
      .addClass(CLASS_BOOK)
      .find('p')
      .text(bookInHTML(value));
  });
}

const CLASS_BOOK = '';
const bookInHTML = arg => arg;
showList(section, ['foo', 'bar']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section"></div>

Upvotes: 4

Related Questions