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!
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!
Share Improve this question asked Apr 6, 2017 at 23:48 BrixstaBrixsta 63714 silver badges26 bronze badges 3-
1
This will append
<strong></strong>
into your paragraph tag... it won't wrap the content within that.... Maybe something like this? jsfiddle/h61r3th9 This will copy the content, construct the strong tag ready for appending, clear the existing content and then replace it with the constructed strong tag. – NewToJS Commented Apr 6, 2017 at 23:50 - 1 Why not just style it with CSS? – j08691 Commented Apr 6, 2017 at 23:53
- 1 I'm trying to challenge myself to e at a problem from a different angle. – Brixsta Commented Apr 6, 2017 at 23:53
4 Answers
Reset to default 4The 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>
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/q9mpa7ws/3/
CSS only approach: https://jsfiddle/hrecvvbj/1/
Styling with JavaScript approach: https://jsfiddle/qynek529/2/
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! :)
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';