I'm trying to bold words inside a string using vanilla javascript (Stricly, no jQuery allowed), so far I have something like this but the string outputs [object HTMLElement]
in the middle of the string.
const fullString = "This is a sentence, please bold the words sentence";
const wordToBold = "sentence";
const boldenWord = (word, fullstring) => {
word = word.toLowerCase();
const boldTextNode = document.createElement("strong");
const textNode = document.createTextNode(word);
boldText.appendChild(textNode);
fullstring = fullstring.replace(keyword, boldText);
return fullstring;
}
const ul = document.createElement('ul');
const li = document.createElement('li')
const liText = document.createTextNode(boldenWord(wordToBold,fullString))
li.appendChild(liText);
ul.appendChild(li);
const outerUL = document.querySelector("#myUlOuter ul")
This ends gives me the following output
<ul>
<li>This is a [object HTMLElement], please bold the words [object HTMLElement]</li>
</ul>
This is a [object HTMLElement], please bold the words [object HTMLElement]
but I'm after
<ul>
<li>This is a <strong>sentence</strong>, please bold the words <strong>sentence</strong></li>
</ul>
This is a sentence , please bold the words sentence
A text string is not of itself bold or otherwise. When rendered as HTML it can produce bold text if it contains <strong> </strong>
tag pairs surrounding text to be rendered in bold.
The first option is to create an HTML source string by inserting strong
tags around word or words in a text string, followed by inserting the HTML into the document. To ensure valid HTML you should also change any <
, >
or &
characters in the input string to HTML character enties <
, >
or &
.
The second option is to create textNodes for portions of the string to be rendered as plain text, interspersed with HTMLElement nodes with tagName "strong".
A strong
element for with specified text content can be created along the lines of
const strongElem = textContent => {
let strong = document.createElement("strong");
strong.textContent = textContent;
return strong;
};
The exercise now becomes
You may still wish to change <
, >
or &
characters in the word to be in bold to their character entity equivalents.
Hoping this helps completing the assignment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.