You're running into a fundamental difference in how JavaScript properties interact with HTML:
element.textContent: Sets or gets the plain text content of an element, stripping all HTML tags.
element.innerText: Similar to textContent, but considers rendering/layout (e.g., won't return text from hidden elements). It also strips HTML tags.
element.innerHTML: Sets or gets the HTML content of an element, including all tags and formatting.
To preserve your bold tag, you need to use innerHTML.
Here are a few ways to solve this, from simplest to safest:
Method 1: Using innerHTML (Simplest, but Caution Advised)
This is the most direct way. You provide the string that includes the HTML tags.
javascript
// Assume you have a paragraph element in your HTML:
// <p id="myParagraph"></p>
const myParagraph = document.getElementById('myParagraph');
const textWithBold = "This is some normal text, and this part is <b>bold</b>.";
myParagraph.innerHTML = textWithBold;
// Result in HTML:
// <p id="myParagraph">This is some normal text, and this part is <b>bold</b>.</p>
CAUTION: Security Risk (XSS)
If textWithBold comes from an untrusted source (like user input from a form or data from a third-party API), directly setting innerHTML can expose your website to Cross-Site Scripting (XSS) attacks. Malicious users could inject harmful scripts.
Only use innerHTML if:
The content is completely static and hardcoded by you.
The content comes from a trusted source that you know has already sanitized all HTML.
Method 2: Building Content with DOM Manipulation (Safer & Recommended for Dynamic Content)
This method involves creating text nodes and elements explicitly, which is much safer when you're dealing with dynamic or potentially untrusted content, as it prevents arbitrary HTML injection.
javascript
// Assume you have a paragraph element:
// <p id="anotherParagraph"></p>
const anotherParagraph = document.getElementById('anotherParagraph');
// 1. Clear existing content (if any)
anotherParagraph.innerHTML = ''; // Or anotherParagraph.textContent = '';
// 2. Create the first text part
const textPart1 = document.createTextNode("This is some normal text, and this part is ");
anotherParagraph.appendChild(textPart1);
// 3. Create the bold element
const boldElement = document.createElement('b');
boldElement.textContent = "bold"; // Use textContent for the bold part to avoid XSS inside it
anotherParagraph.appendChild(boldElement);
// 4. Create the second text part (if needed)
const textPart2 = document.createTextNode(".");
anotherParagraph.appendChild(textPart2);
// Result in HTML:
// <p id="anotherParagraph">This is some normal text, and this part is <b>bold</b>.</p>
Pros:
Secure: You control exactly which elements are created and what their plain text content is. You can't accidentally inject scripts this way.
Flexible: Easy to add other elements (<em>, <span>, <a>, etc.) or more complex structures.
Cons:
More verbose for very complex text structures with many mixed tags.
Method 3: Using a Sanitization Library (Best for User-Generated Rich Text)
If you need to accept rich text (with formatting) from users or an untrusted source, the most secure approach is to use a HTML sanitization library. A popular and robust one is DOMPurify.
Install DOMPurify:
If using npm/webpack: npm install dompurify
If via CDN: Add <script src="https://cdn.jsdelivr.net/npm/dompurify@2.x/dist/purify.min.js"></script> to your HTML.
Use DOMPurify:
javascript
// Assume you have a paragraph element:
// <p id="sanitizedParagraph"></p>
const sanitizedParagraph = document.getElementById('sanitizedParagraph');
// Example of potentially unsafe user input:
const userInput = "This is user-submitted text. It might contain <b>bold</b> text or even <script>alert('malicious code!');</script>";
// Sanitize the input
const cleanHTML = DOMPurify.sanitize(userInput);
// Now it's safe to use with innerHTML
sanitizedParagraph.innerHTML = cleanHTML;
// Result in HTML (script tag removed by DOMPurify):
// <p id="sanitizedParagraph">This is user-submitted text. It might contain <b>bold</b> text or even </p>
Pros:
Highly Secure: Protects against a wide range of XSS attacks.
Automated: You don't have to manually parse and build DOM elements.
Configurable: You can configure DOMPurify to allow or disallow specific tags, attributes, etc.
Cons:
Adds an external dependency.
Which method should you choose?
If the text is static and hardcoded by you (or comes from a perfectly trusted, pre-sanitized source): Use innerHTML (Method 1).
If you are constructing the text dynamically in your JavaScript code and want maximum security without external libraries (e.g., you know exactly which words should be bolded, not based on user input): Use DOM Manipulation (Method 2). This is generally the safest default for dynamically building HTML.
If the text comes from user input or any untrusted source and needs to include formatting: Use a HTML Sanitization Library like DOMPurify (Method 3) before setting innerHTML. This is the professional way to handle user-submitted rich text.
User
but i have the already the bold tag, something like this: <p id='sets'><b>sets: </b></p>, and via js it would be something like this: node.textContent += variable. i need something that would work with a similar solution
Assistant
You're absolutely right to point out that textContent += variable will destroy your existing <b> tag because textContent operates on the plain text representation of the element's content.
To preserve your <b> tag and append new text after it, you need to either:
Manipulate the innerHTML of the paragraph.
Use DOM manipulation to append a new text node.
Let's break down the solutions based on whether your variable contains plain text or HTML, and its origin (trusted vs. untrusted).
Your Initial HTML:
html
<p id='sets'><b>sets: </b></p>
Method 1: Using innerHTML += (Simplest, but Caution for Untrusted Input)
This is the most direct way to append content while preserving existing HTML.
javascript
const paragraph = document.getElementById('sets');
const variable = "123"; // Or whatever dynamic value you have
// Solution: Append to innerHTML
paragraph.innerHTML += variable;
// Result in HTML:
// <p id='sets'><b>sets: </b>123</p>
Why it works:paragraph.innerHTML initially gives you "<b>sets: </b>". When you use +=, it appends variable to that string, resulting in "<b>sets: </b>123", and then that entire string is written back to the innerHTML, preserving the bold tag.
CAUTION: If variable comes from an untrusted source (like user input from a form or an external API), directly using innerHTML += variable can expose your site to Cross-Site Scripting (XSS) attacks. A malicious user could inject <script> tags.
Use this method ONLY if:
variable is hardcoded by you.
variable comes from a trusted source and you are absolutely certain it contains only the plain text or safe HTML you expect.
Method 2: Appending a New Text Node (Safest for Plain Text)
This is the recommended approach if your variable always contains plain text and you want to ensure no HTML injection (even accidental or from untrusted sources).
javascript
const paragraph = document.getElementById('sets');
const variable = "456"; // Again, your dynamic value
// Solution: Create a new text node and append it
const newTextNode = document.createTextNode(variable);
paragraph.appendChild(newTextNode);
// Result in HTML:
// <p id='sets'><b>sets: </b>456</p>
Why it works:
document.createTextNode(variable) creates a plain text node. HTML characters like <, > are automatically escaped.
paragraph.appendChild() adds this new text node as the last child of the <p> element. Since the <b> tag is the first (and only) child initially, the new text node is added after it, preserving the <b> tag.
Pros:
Secure: Prevents XSS because you're explicitly creating a text node, not parsing a string as HTML.
Clean DOM: Directly adds a text node to the DOM.
Cons:
Slightly more verbose than innerHTML +=.
Can only append plain text this way. If variable itself needed to contain HTML (e.g., variable = "<em>important</em>"), this method would render the HTML tags as literal text (<p><b>sets: </b><em>important</em></p>).
Method 3: Using a Sanitization Library (Best for Untrusted HTML Input)
If your variable might contain HTML (e.g., user-submitted rich text from a WYSIWYG editor) and is from an untrusted source, you must sanitize it before inserting it into the DOM. DOMPurify is the gold standard for this.
Install DOMPurify:
Via npm: npm install dompurify
Via CDN: Add <script src="https://cdn.jsdelivr.net/npm/dompurify@2.x/dist/purify.min.js"></script> to your HTML.
Use it:
javascript
// Assuming DOMPurify is loaded
const paragraph = document.getElementById('sets');
// Example: User input that might be malicious or contain desired HTML
const variable = "789 and some <em>emphasized</em> text. <script>alert('bad!');</script>";
// Solution: Sanitize the variable before appending
const cleanHTML = DOMPurify.sanitize(variable);
paragraph.innerHTML += cleanHTML;
// Result in HTML (script tag removed by DOMPurify):
// <p id='sets'><b>sets: </b>789 and some <em>emphasized</em> text. </p>
Pros:
Highly Secure: Protects against XSS while allowing desired HTML tags.
Flexible: Handles both plain text and rich HTML content.
Cons:
Adds an external dependency.
Summary & Recommendation:
For plain text variable (most common scenario): Use Method 2 (Appending a New Text Node). It's safe, clear, and handles the <b> tag preservation perfectly.
For trustedvariable (plain text or HTML): Use Method 1 (innerHTML +=). It's concise.
For untrustedvariable that might contain HTML: Use Method 3 (DOMPurify). This is the only safe way.
Given your specific example (node.textContent += variable), it seems you're likely dealing with plain text variable. Therefore, Method 2 (paragraph.appendChild(document.createTextNode(variable));) is generally the best and safest solution for your needs.