0

I have a JQuery function, in which I define a span element. I just want to replace the "130px" with a variable. I have a variable with the value "width:130px". I obviously don't know how to put it in there. Thank you for any ideas!

link.append('<span class="title" style="width:130px">' + item.title + '</span>');
1
  • link.css('width', yourVar). .css can also take an Object. Commented Jun 18, 2020 at 0:37

3 Answers 3

1

use + to concatenate strings.

link.append('<span class=\"title\" style=\"width:'+ variable + '\">' + 21 + '</span>');

or use link.css({"width": yoursVariable})

In css() use camalCase in properties names

link.css({"backgroundColor": "red"})
Sign up to request clarification or add additional context in comments.

1 Comment

Yes it's the missing "+". Thank you all guys!
1

You can see I concanated a JS variable withing the <span></span> tags. Have a look at the example.

Please remember to add display: block to your span element in order to see the effect of the width.

let link = $(".link")
let myWidth = '130px'
link.append('<span class="title" style="display: block; background-color: red; width:'+myWidth+'">' + 'title' + '</span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="link">test</div>

Comments

0

Use this link.css('width', '300px');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.