1

I have a variable and use it for creating an HTML element with a class attribute:

var my_class="my_class";
$(this).after("<div class="+my_class+"></div>");

I get <div class="my_class"></div> as expected, but when adding a variable with space in it:

var my_class="my_class id";
$(this).after("<div class="+my_class+"></div>");

I get <div class="my_class" id></div> instead of <div class="my_class id"></div>. How can I change that?

4
  • 1
    Best to avoid all these pitfalls and assign the attribute directly: $(this).after($("<div></div>").attr('class', my_class)); Commented Aug 1, 2021 at 13:00
  • 1
    String composition is the worst way to generate HTML, and this is the main reason. Note that you can use single quotes: "<div class='"+my_class+"'></div>" or a template literal: `<div class="${my_class}"></div>` instead. Commented Aug 1, 2021 at 13:04
  • Here's what I'd do: const $div = $('<div>'); then div.addClass('my_class').addClass('id'); (or both at once) then $(this).after($div); Commented Aug 1, 2021 at 13:07
  • Or $("<div/>", { "class": "my_class id" }) Commented Aug 1, 2021 at 13:16

1 Answer 1

6

You seem to be expecting that " is part of the HTML? Because executing (part of) your code results in the following string:

const my_class="my_class id";
console.log("<div class="+my_class+"></div>");

That gives <div class=my_class id></div>, i.e. no " for class. So add them by adding escaped quotes:

const my_class="my_class id";
console.log("<div class=\""+my_class+"\"></div>");

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.