Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

Adding HTML tags in a javascript variable


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As noted - you have the plus in the code and the browser is rendering it as a string amnd the rest of the h1 is then a string as well - not a html element of <h1>. If I understand your needs - you are trying to make a string and then have that rendered.

That way you can create the elements dynamically, add icons and other html elements and then add it into the DOM using innerHTML().

let headingStr = '';

headingStr += '<h1>';
  headingStr += '<span class="icon">~</span>';
  headingStr += 'This is a heading';
  headingStr += '<span class="icon">*</span>';
headingStr += '</h1>';

document.querySelector('#container').innerHTML = headingStr;
#container {
  padding: 8px 16px;
  border: solid 1px blue;
}
h1 {
  font-size: 18px;
  color: green;
  margin: 0;
 }
 
.icon {
   color: red;
}
<div id="container"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...