Aiya Siddig
Aiya Siddig

Reputation: 111

How can I bold an appended text using javascript?

Working on a project in which I'm wanting to make the appended text appear bold. Based on my research it should be .bold() but that's not making my appended text bold, and is instead showing my text surrounded by "< b >< /b >". What am I doing incorrectly? Here is my code:

var breweryname=response.results[i].name;
    var breweryName = $("<p class='title'>").text(response.results[i].name.bold());
    breweryDiv.append(breweryName);

Upvotes: 0

Views: 1008

Answers (2)

Daniel A. White
Daniel A. White

Reputation: 191058

Instead of using .text(), use .html() (ensure that you trust the response - you don't want any injection!) You could also make your CSS class title with font-weight: bold if you'd like to separate behavior and presentation.

Upvotes: 1

Always Helping
Always Helping

Reputation: 14570

I would suggest not using .html() as it could have injections (Which you should avoid). .name is just a text name which you want it bold then keep using .text.

To apply css (bold fonts) to your dynamically added elements (response.results[i].name).

You can simply use jQuery .css function which will let you design your element as exactly as normal css is a much better approach.

Run snippet below to see it working.

//Div to append to
var breweryDiv = $('#breweryDiv')

//Response
var breName = 'Random Name' //response.results[i].name;

//Text
var breweryName = $("<p class='title'>").text(breName);

//Apply Css
$(breweryName).css({
  'font-weight': 'bold'
})

//Append Results
breweryDiv.append(breweryName);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="breweryDiv">

</div>

Upvotes: 2

Related Questions