I’m trying to render this dynamically using jQuery .append() :
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" style="color: white" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<p>
<strong>Error!</strong> My error message
</p>
</div>
But I can’t seem to get the p tag text after the strong text. It’s either before the strong or it overwrites the strong text. This is what I’ve tried:
$('#error-div').append(
$('<div>').prop(
{
class: 'my-class-name',
role: 'alert',
}
).append(
$('<button>').prop({
type: 'button',
class: 'close',
style: 'color: white',
}).attr(
{
'data-dismiss': 'alert',
'aria-label': 'Close'
}
).append(
$('<span>').attr(
{
'aria-hidden': true,
}).html('×')
)
).append(
$('<p>').append(
$('<strong>').html('Error! ')
).html('My error message')
))
But this renders:
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close" style="color: white;">
<span aria-hidden="true">×</span>
</button>
<p>My error message</p>
</div>
How do I get the strong tag inside the p tag, before the p text?
2
Answers
This is how I did it:
Here is the JSFiddle demo
Consider building the nodes then appending them to each other and then applying it all to the page element. OR use content templates and avoid the complication Ref:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
Note I used differing text just to show one from the other with a J and T at the end.