3

There are quite a few similar questions, but none are quite what I need nor can I fiddle them around to fit what I'm trying to do.

I have the following:

document.querySelector('#output').innerHTML = 'Hi ' + name; 

And would like to, somehow, add the <span> tags around name using the above. I'm attempting to create a simple chat AI for fun, and want to be able to hightlight certain words that the AI is saying.

1
  • is this what you want? document.querySelector('#output').innerHTML = 'Hi <span>' + name + "</span>"; Commented Sep 21, 2014 at 4:20

4 Answers 4

5

Just add the spans in your string:

document.querySelector('#output').innerHTML = 'Hi <span>' + name + '</span>'; 
Sign up to request clarification or add additional context in comments.

1 Comment

Ohhh okay, I was adding them as separate tags, not inside the string. Thanks!
4

You can also try by storing the node and append the child .

       var First;
       First=document.getElementById("basic").value;
       var v = document.createElement("p");
       v.appendChild(document.createTextNode(First));
       document.getElementById("fd").appendChild(v);

1 Comment

In shorter, this also works: var edv=document.getElementById("plot"); var edp=document.createElement("span"); edv.appendChild(edp); edp.innerHTML="Hello world";
1

If you want some programatically, if you are looking for some span simply appearing in the screen:

var esp=document.createElement("span");
document.getElementById("mydiv").appendChild(esp);
esp.innerHTML="This is my span";

Comments

0

If you are looking to do it programmatically, create your span using JS.

var name = 'Asteria';
var x = document.createElement('span');
x.id = 'highlight';
x.innerText = name;

document.querySelector('#output').innerHTML = 'Hi ' + x.outerHTML;

and you can use CSS to highlight the span with ID using

#highlight { color: red; }

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.