How can I make text bold with nodes and .createElement("b")? - javascript

I have to make text bold if I click on a button using nodes and createElement but I don't really know how...
html (This is the text I want to make bold):
<p id="textalt">Dies ist ein Text in einem P-Tag</p>
javascript:
function fettmachen(){
var neuB = document.createElement("b");
document.getElementById("textneu").insertBefore(neuB, document.getElementById("textneu").nextSibling);
}
I don't know how it works.

"I have to do it with nodes and createElement"
function fettmachen(){
// create the "b" element
var neuB = document.createElement("b");
// fetch the "textneu" element by ID
var textneu = document.getElementById("textneu");
// append the firstChild of "nextneu" to the "neuB"
neuB.appendChild(textneu.firstChild);
// append the "neuB" to the "nextneu"
nextneu.appendChild(neuB);
}

I suggest, instead of adding new tags, just use CSS, and add a class to the element.
CSS:
.boldText{
font-weight: bold;
}
JavaScript:
function fettmachen(){
document.getElementById("textalt").className += ' boldText';
}

I'd just put a style on the <p> tag on the button press. Maybe something like...
function fettmachen(){
var neuB = document.getElementById("textalt");
neuB.style.fontWeight = "bold";
}

Well, you could use the following code. It's longer and could be condensed - I find it clearer to read, personally.
function fettmachen()
{
var pElem = document.getElementById('textAlt');
var text = pElem.innerHTML;
var bElem = document.createElement('b');
bElem.innerHTML = text;
pElem.innerHTML = '';
pElem.appendChild(bElem);
}

This is how you make the text bold
function fettmachen(){
var p = document.getElementById("textneu");
p.style.fontWeight = "bold;"
}

If you have to use js for some reason for instance you need to only bold certain words maybe, and don't have access to the style sheet here you go. Otherwise use what Rocket has suggested.
Seriously only use a solution like this if at some point you will need to only bold certain words, or groups of words within an element.
function fettmachen(){
var neuB = document.createElement("b"),
textEl = document.getElementById("textalt"),
text = textEl.textContent;
neuB.textContent = text;
textEl.textContent = "";
textEl.appendChild(neuB);
}
Live Demo
And to unbold.
function unbold(){
var textEl = document.getElementById("textalt"),
boldEls = textEl.getElementsByTagName("b"),
text = "";
for(var i = 0; i < boldEls.length; i++){
text+=boldEls[i].textContent;
textEl.removeChild(boldEls[i]);
}
textEl.textContent = text;
}
Live Demo 2

Related

How can I write down paragraphs in HTML with Javascript without the use of getElementbyId?

So, i was working on this little formatting experiment with HTML, where you could create a paragraph via input and it would create an HTML paragraph on the screen. I did it by doing this.
HTML:
<button onclick="create_para()">Create Paragraph</button>
<p id="p1"></p>
Javascript:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
document.getElementById("p1").innerHTML = p;
}
And, it worked! The only problem is that I wanted it so you could click the button again and again and it would create new paragraphs without replacing the old one. The only way I thought I could do it would be by making a bunch of tags with different classes, and having a bunch of functions, and a lot of buttons, but that's inefficient and too complicated.
So, I found out about document.write() and document.writeln(). So I used it in my code, but turns out it just deletes all other HTML code and just leaves it with the lines I wrote.
Therefore, is the a form of writing down paragraph lines without the use of ID's, or a form where it wouldn't delete all HTML code?
Thanks.
You can do something like:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
document.body.appendChild(elem)
}
EDIT: to add an id to each, you can add a global counter variable.
var i = 0;
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
elem.id = '' + i;
i++;
document.body.appendChild(elem);
}
You can create a div container and then creates HTML Elements dinamically with your function, also you can assing an id to your new element, try this:
let div = document.getElementById('container');
function create_para(){
let p = document.createElement('p');
let txt = window.prompt("Enter paragraph text: ");
p.textContent = txt;
p.id = 'your id';
div.appendChild(p);
}
<div id='container'></div>

How to extract text from an HTML node and maintain the correct space formatting with JavaScript?

I need to get the text value inside of a div. You can think of it like a text area, where you can do like this:
let inputArea = document.getElementById("text-area");
let text = inputArea.value;
text
// Expected result:
// Hello
//
// Hello
//
// Hello
//
// Hello
Unfortunately, I don't have a text area and I can't do that. So what here's what I did:
(1) Get the HTML node where I need to extract the text (var bodyHtml..)
(2) Convert the HTML node to string (calling extractStringFromNode()..)
(3) Extract the string out of the returned string (calling extractContentFromString()..)
My problem is that I lose the "text formatting". The let text (code above) contains the value of the inputArea with the proper formatting. I lose this when I try to reproduce it using my implementation (code below).
What is the right way to solve this?
var OriginalText;
function parseText(event) {
// get text
var bodyHtml = event.composeView.getBodyElement();
var stringBodyHtml = extractStringFromNode(bodyHtml);
console.log(stringBodyHtml)
var text = extractContentFromString(stringBodyHtml);
OriginalText = text;
console.log(text);
// now parse it
format(text);
}
// extract text from html
function extractContentFromString(s) {
var span = document.createElement('span');
span.innerHTML = s;
return span.textContent || span.innerText;
};
// from html node to string
function extractStringFromNode ( node ) {
var tmpNode = document.createElement( "div" );
tmpNode.appendChild( node.cloneNode( true ) );
var str = tmpNode.innerHTML;
tmpNode = node = null; // prevent memory leaks in IE
return str;
}
// Expected result: HelloHelloHelloHello
Use the CSS property white-space and set it to pre. This will preserve line breaks, however, you must place it in every place you want to have the text with similar spacing.
let div = document.querySelector("div");
//this div has CSS styling white-space: pre
span = document.body.appendChild( document.createElement("span") );
//this span does not
span.textContent = div.textContent;
//div will be "formatted" with line breaks. Span will not.
div {
white-space: pre;
}
<div>This
Is
A
Demo
</div>
<hr/>

javascript dynamically remove text

I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:
var addButtons = document.querySelectorAll('.add button');
function addText () {
var self = this;
var weekParent = self.parentNode.parentNode;
var textarea = self.parentNode.querySelector('textarea');
var value = textarea.value;
var item = document.createElement("p");
var text = document.createTextNode(value);
item.appendChild(text)
weekParent.appendChild(item);
}
function removeText() {
//document.getElementbyId(-).removeChild(-);
}
for (i = 0; i < addButtons.length; i++) {
var self = addButtons[i];
self.addEventListener("click", addText);
}
I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.
Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.
function removeText() {
var weekParent = this.parentNode.parentNode;
var item = weekParent.querySelector("p");
weekParent.removeChild(item);
}
If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.

Need help changing appendChild to replaceChild

Is there an easy way to change this from appendChild to replaceChild?
This of course continuously adds more ele. Also for some reason it doesn't put the value inside the DIV or SPAN, seems to put below it.
var para = document.createElement("P");
var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;
para.appendChild(total);
document.getElementById("total_id").appendChild(para);
Its updating this:
<div class="prod_totals">Order Total: $<span id="total_id"></span></div>
you can simply use innerHTML instead of appendChild
document.getElementById("total_id").innerHTML = parseFloat((subT + tax).toFixed(2));
Because you're not inserting any user input values inside the total_id element and also as far as the question mentions, its data is not later passed to the server I think you'll be safe using the innerHTML here. But if for any reasons you'd still like to use replaceChild you could do it like this:
var para = document.createElement("P");
var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;
para.appendChild(total);
var existingText=document.getElementById("total_id").querySelector('p');
if(existingText){
document.getElementById("total_id").replaceChild(existingText, para);
}
else{
document.getElementById("total_id").appendChild(para);
}
There's no need to use .replaceChild here, you can simply check if the element was already created before trying to update it.
Note that you were trying to insert a p element inside a span which is wrong and is not valid HTML markup, you can see in the span documentation that its possible content is only Phrasing content, so you better use another span.
This is how should be your code:
var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
para = document.createElement("span");
}
var total = parseFloat((subT + tax).toFixed(2));
para.innerText = total;
document.getElementById("total_id").appendChild(para);
And here's a Demo:
var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
para = document.createElement("span");
}
var total = new Date();
para.innerText = total;
document.getElementById("total_id").appendChild(para);
<div class="prod_totals">Order Total: $<span id="total_id"></span></div>

Turn jQuery into vanilla JS - Insert p element after h1

Any ideas on how I would convert this jQuery to vanilla JS:
$('.section > h1').after('<p>This paragraph was inserted with jQuery</p>');
I am new to jQuery and even newer to vanilla JS.
This is as far as I got:
var newP = document.createElement('p');
var pTxt = document.createTextNode('This paragraph was inserted with JavaScript');
var header = document.getElementsByTagName('h1');
Not sure where to go from here?
jQuery does a lot for you behind the scenes. The equivalent plain DOM code might look something like this:
// Get all header elements
var header = document.getElementsByTagName('h1'),
parent,
newP,
text;
// Loop through the elements
for (var i=0, m = header.length; i < m; i++) {
parent = header[i].parentNode;
// Check for "section" in the parent's classname
if (/(?:^|\s)section(?:\s|$)/i.test(parent.className)) {
newP = document.createElement("p");
text = document.createTextNode('This paragraph was inserted with JavaScript');
newP.appendChild(text);
// Insert the new P element after the header element in its parent node
parent.insertBefore(newP, header[i].nextSibling);
}
}
See it in action
Note that you can also use textContent/innerText instead of creating the text node. It's good that you're trying to learn how to directly manipulate the DOM rather than just letting jQuery do all the work. It's nice to understand this stuff, just remember that jQuery and other frameworks are there to lighten these loads for you :)
You might find this function useful (I didn't test)
function insertAfter(node, referenceNode) {
referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
}
Oh it's not so bad...
var h1s = document.getElementsByTagName('h1');
for (var i=0, l=h1s.length; i<l; i++) {
var h1 = h1s[i], parent = h1.parentNode;
if (parent.className.match(/\bsection\b/i)) {
var p = document.createElement('p');
p.innerHTML = 'This paragraph was inserted with JavaScript';
parent.insertBefore(p, h1.nextSibling);
}
}

Categories