Brixsta
Brixsta

Reputation: 625

Bolding a text node in the DOM

I am trying to bold text in my paragraph, but am not sure what to append exactly. Here is my code.

<p id="para">
  Hello World
</p>

var para = document.getElementById('para');
var bold = document.createElement('STRONG');

para.appendChild(bold);

Any thoughts?

Thanks!

Upvotes: 2

Views: 9101

Answers (4)

Miguel
Miguel

Reputation: 20633

To replace text content with strong element:

// Get paragraph element
var para = document.getElementById('para');

// Create a strong node
var bold = document.createElement('strong');

// Get first child element of paragraph which is a text node
var textNode = para.firstChild;

// Append text to new strong node
bold.appendChild(document.createTextNode(textNode.nodeValue));

// Replace old text node with new strong node
para.replaceChild(bold, textNode);

JS Fiddle Demo: https://jsfiddle.net/q9mpa7ws/3/

CSS only approach: https://jsfiddle.net/hrecvvbj/1/

Styling with JavaScript approach: https://jsfiddle.net/qynek529/2/

Upvotes: 2

Yatrix
Yatrix

Reputation: 13775

Try to keep your concerns as separated as you can. Create a css class and apply it.

// in your css
.bold {
    font-weight: bold;
}

// in your javascript
para.className = 'bold';

Upvotes: 0

kind user
kind user

Reputation: 41893

The strong element has to contain a textnode.

var para = document.getElementById('para'),
    bold = document.createElement('strong'),
    textnode = document.createTextNode("I'm bold!"); 
    bold.appendChild(textnode); 
    
    para.appendChild(bold);
<p id="para">
  Hello World
</p>

Upvotes: 4

Obsidian Age
Obsidian Age

Reputation: 42304

You don't need to worry about appending a new node at all; simply alter the font-weight through JavaScript's fontWeight DOM Style Object:

document.getElementById("para").style.fontWeight = "bold";
<p id="para">
  Hello World
</p>

Hope this helps! :)

Upvotes: 1

Related Questions