0

I have a very old Rails 3 project I'm maintaining, to which I need to add new functionality. Primarily responsiveness with Bootstrap 4.

This is what I actually want to create: http://jsfiddle.net/k1zbe4o9/. As you can see it works perfectly in the fiddle. However this project uses jQuery to dynamically change HTML. The jQuery code is fairly simple

if (best_price) {
  li_class = "list-group-item";
  li_class += " card-list-best";
}

I use this in function like so:

var list_html = $("<li class=" + li_class + ">" + list_details_html + "</li>");

However, when I do this I get this weird thing that the jQuery doesn't return this properly, so instead of having list-group-item card-list-best inside a single <li> class, somehow I get card-list-best outside that scope, and the result is as shown.

The same thing happens if I do:

if (best_price) {
  li_class = "list-group-item card-list-best";
}

Any help is appreciated.

jquery segment

2
  • why are you using jQuery for this? Commented Sep 29, 2020 at 8:13
  • 1
    The problem is because of the spaces in the class attribute you're trying to set. You need to wrap the entire attribute value in quotes for the space to be respected within the value. This isn't a jQuery issue, it's part of the HTML standard. Commented Sep 29, 2020 at 8:16

1 Answer 1

3

You can add ' when you build the li.

"<li class='" + li_class + "'>" + list_details_html + "</li>"

as you can see in the example, I've added a console log, it returns <li class=list-group-item card-list-best>test</li> so if there no " or ' after class= then it will take the value after = and until the first space, so it would return <li class="list-group-item">test</li>

Working example

var li_class = "";
var list_details_html = "test";
li_class = "list-group-item";
li_class += " card-list-best";
var list_html = $(
  "<li class='" + li_class + "'>" + list_details_html + "</li>"
);

console.log("<li class=" + li_class + ">" + list_details_html + "</li>")

$('ul').append(list_html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul></ul>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.