admin管理员组文章数量:1323734
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';
本文标签: javascriptBolding a text node in the DOMStack Overflow
版权声明:本文标题:javascript - Bolding a text node in the DOM - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742118420a2421578.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论