skip to Main Content

Please help me add the html div tag in the script

const button = this.createElement("div");

button.classList.add("start_button");
let border = 0;
if (typeof this.config.backgroundImg === "string") {
  button.classList.add("button");
  border = 1;
}
button.innerText = (typeof this.config.startBtnName === 'string') 
                 ? this.config.startBtnName 
                 : this.local("test");

this.config.startBtnName is a text, i need this text to be inside <div>

I tried this '<div>'+this.config.startBtnName+'</div>', but then the div is output as plain text, not an html tag.

2

Answers


  1. To insert HTML content, including a div tag, into a JavaScript-created element, you should use the innerHTML property instead of innerText. The innerText property treats the assigned value as plain text and does not parse it as HTML. However, innerHTML will treat the assigned value as HTML, allowing you to insert tags like div.

    Here’s how you can modify your code to include the div tag:

    const button = this.createElement("div");
    button.classList.add("start_button");
    let border = 0;
    
    if (typeof this.config.backgroundImg === "string"){
        button.classList.add("button");
        border = 1;
    }
    
    // Using innerHTML to insert div tag
    button.innerHTML = (typeof this.config.startBtnName === 'string') 
        ? '<div>' + this.config.startBtnName + '</div>' 
        : '<div>' + this.local("test") + '</div>';
    

    In this code, innerHTML is used to set the content of the button. If this.config.startBtnName is a string, it wraps that string in a div tag. Otherwise, it falls back to using the result of this.local("test"), also wrapped in a div tag.

    Please ensure that this.config.startBtnName and the return value of this.local("test") are properly sanitized if they can include user input, to avoid potential security risks such as Cross-Site Scripting (XSS).

    Login or Signup to reply.
  2. You could use document.createElement to make a div element, then add the text to it.

    const div = document.createElement('div'); // consider using span instead
    div.append(typeof this.config.startBtnName === 'string' ? this.config.startBtnName : this.local("test"));
    button.replaceChildren(div);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search