I'm attempting to create a text element and then add CSS attributes
I've tried to use the code below
function create(text){
var t = document.createTextNode(text);
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
I expect to create a text with a white background and 20px border radius with a 4px solid black border
Instead of a text node, which I don't think you can add styles to, just use a span instead
function create(text){
var t = document.createElement("span");
t.innerText = text;
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
You are having trouble because text nodes are not meant to be styled.
You should create a DOM element instead. I took your code and update it in order to create a <p> (the nearest element of text node I guess) with your CSS:
function create(text) {
var t = document.createElement('p');
t.innerText = text;
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
You are on the right direction. The only thing you need to do is change document.createTextNode(text) with:
var t = document.createElement('span');
t.innerText = text;
\\...
document.body.appendChild(t);
The reason why your code doesn't work is that you can only style HTML tags, and the the text node you created only contains the string you added, without a surrounding tag.
For example:
<span>
hello
</span>
is a tag with some text with it, while the hello text in the middle is a TextNode.
Hope this makes sense.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
Related
I am trying to make a function that creates divs containing text and puts them in another div called "history".
The problem is that the text in the divs come out as single lines like this
2/2=1
instead of this
2/2
=1
It may also be caused by the height limitation of the div, if so how do I automatically adjust the size with javascript.
function creatediv() {
var element = document.createElement("div");
var doc = "2/2" + "\n" + "=1";
const es = element.style;
element.appendChild(document.createTextNode(doc));
document.getElementById('history').appendChild(element);
es.backgroundColor = "azure";
es.margin = "3px"
es.borderRadius = "5px";
es.padding = "2px"
}
Use the CSS property white-space: pre which makes line-breaks (and other whitespace) inside HTML #text nodes visible.
white-space is exposed in the DOM as CSSStyleDeclaration.whiteSpace.
Values are set as normal strings, e.g. 'pre' or 'normal'.
e.g.: document.getElementById('abc123').style.whiteSpace = 'pre';
You don't need element.appendChild(document.createTextNode(doc));, you can set .textContent directly.
Like so (click "Run code snippet"):
function createDiv() {
const div = document.createElement("div");
div.textContent = "2/2\n=1";
const s = div.style;
s.backgroundColor = "azure";
s.margin = "3px";
s.borderRadius = "5px";
s.padding = "2px";
s.whiteSpace = 'pre'; // <-- Right here.
document.getElementById('history').appendChild( div );
}
<button type="button" onclick="createDiv()">Create DIV</button>
<div id="history" style="border: 3px inset #999"></div>
I have a sentence and I am trying to replace globally one word by an under-line of equal space. That is:
Example: This is my first text, this is my second text and this is my third text.
NewExample: This is my first ____, this is my second ____ and this is my third ____.
My question is related with this question How to change color of a word in a sentence by clicking it on PC or by touching it on Android and the excellent answer of #terrymorse. So, I want to use somehow the following in the replace function:
// span.style.color = 'yellow';
// span.style.width = span.getBoundingClientRect().width + 'px';
// span.innerHTML = '_';
// span.style.borderBottom = '2px solid yellow';
This is my full example but only color works. Could you please someone help me and tell me what I am doing wrong with the rest of them?
<div id='Example'>This is my first text, this is my second text and this is my third text.</div>
<div id='Split'>text</div>
<div id='NewExample'></div>
fReplace(Example, Split)
function fReplace(Example, Split) {
v1 = Example.innerText;
function myFunction(word) {
var reg = new RegExp(word, "g");
v1 = v1.replace(reg, `<span style = "color: yellow; word.borderBottom: 2px solid yellow; width: word.getBoundingClientRect().width + 'px'; word.innerHTML: '_'">${word}</span>`)
}
Split.forEach(myFunction);
document.getElementById('NewExample').innerHTML = v1;
}
You can create a function that replaces the target text with a span element. The span element will be used to display the underline. I created a function named replaceTextWithUnderline in the code snippets below that demonstrates the expected behavior.
I thought of two different approaches to display the underline. Hopefully, one of these approaches fits your use case:
Approach 1: Making the text color transparent and wrapping the target text in <span> tags
This approach is straightforward. It involves replacing the target text with the target text wrapped inside of <span> tags.
function replaceTextWithUnderline(words, targetText = 'text') {
const regex = RegExp(targetText, 'gi')
const styles = `
color: transparent;
border-bottom: 2px solid yellow;
`
return words.replace(regex, `<span style="${styles}">${targetText}</span>`)
}
function fReplace() {
const exampleEl = document.getElementById('Example')
const newExampleEl = document.getElementById('NewExample')
newExampleEl.innerHTML = replaceTextWithUnderline(exampleEl.innerText)
}
fReplace()
<div id='Example'>This is my first text, this is my second text and this is my third text.</div>
<div id='NewExample'></div>
Positive aspects to this approach are that the underline's width will be equal to the target text's width and that you can achieve the same result using classes and CSS. For example:
<!-- Generated HTML from Javascript -->
<span class="underline">target text</span>
/* Accompanying styles for generated HTML */
.underline {
color: transparent;
border-bottom: 2px solid yellow;
}
A negative aspect is that this may not be a solution if you do not want any text inside of the <span> tags.
Approach 2: Using ch to define the underline's width
If you do not want any text inside of the <span> tags, you can opt to using the following CSS:
/* To apply a width, we need to change the display from inline to inline-block. */
display: inline-block;
/* <number> represents the number of characters in the target text */
width: <number>ch;
function createUnderlineStyles(numberOfChars) {
return `
display: inline-block;
width: ${numberOfChars}ch;
border-bottom: 2px solid yellow;
`
}
function replaceTextWithUnderline(words, targetText = 'text') {
const regex = RegExp(targetText, 'gi')
const styles = createUnderlineStyles(targetText.length)
return words.replace(regex, `<span style="${styles}"></span>`)
}
function fReplace() {
const exampleEl = document.getElementById('Example')
const newExampleEl = document.getElementById('NewExample')
newExampleEl.innerHTML = replaceTextWithUnderline(exampleEl.innerText)
}
fReplace()
<div id='Example'>This is my first text, this is my second text and this is my third text.</div>
<div id='NewExample'></div>
This utilizes the ch unit. From MDN's documentation, the ch unit is:
The advance measure (width) of the glyph "0" of the element's font.
This approach can be used if you do not want any text inside of the <span> tags. However, downsides to this approach are that the underline's width will not exactly match the target text's width and you will most likely not be able to implement this with CSS due to the nature of the number of characters being dynamic.
I'm trying to make a button create new entries in a list that display similar to this:
"#1 new Click Me"
Except I want to make "Click Me" to show up as yellow text in a black box, and then I want to make the black box disappear and the text turn brown on mouseover. I've been able to make the list appear, but don't know how to edit the style of the text to make it appear the way I want to. The most code I think I need to give for this is this:
var li = document.createElement("li");
var liBody = document.createTextNode("#"+numOfNewCMs+
" new " + newClickMe);
li.appendChild(liBody);
And then I insert li into the list.
I figure I should make newClickMe a variable and edit that and then put it next to the rest of the text in the liBody variable, and I figure the HTML span element is the best way to do that, except I don't even know quite what the span element really does. How do I go about editing the style of that particular string? I can't get around to figuring out how (if I even can) make the text turn brown on mouseover until I do so.
Never met CreateTextNode, but i guessliBody.style.fontSize="12px"should help. And other properties such as 'fontWeight,color,fontStyle...'
HTML elements have a style property that can be used to apply CSS styles to them.
For example:
var newClickMe = document.createElement("span");
newClickMe.style.backgroundColor = "#000000";
newClickMe.style.color = "#FFFF00";
newClickMe.innerText = "Click Me";
var li = document.createElement("li");
var liText = document.createTextNode("#"+numOfNewCMs+
" new ");
li.appendChild(liText);
li.appendChild(newClickMe);
Will make the list item have a black background with yellow text.
For more details on the style property, MDN has a great section on it: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
And here is a reference page to translate CSS properties into their JavaScript equivalent: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference
I'm assuming you want the styles to change on mouseOver. I just changed the styles using css' :hover. Is this what you had in mind?
var numOfNewCMs=1;
function generateLi(){
var li = document.createElement("li");
var liBody = document.createTextNode("#"+numOfNewCMs+
" new ");
var sp = document.createElement("span");
var spBody = document.createTextNode("Click Me");
sp.setAttribute("id", "sp"+numOfNewCMs);
sp.setAttribute("onmouseover", "highlight("+numOfNewCMs+")");
sp.setAttribute("onmouseout", "highlight2("+numOfNewCMs+")");
sp.style.backgroundColor='black';
sp.style.color='yellow';
sp.appendChild(spBody);
li.appendChild(liBody);
li.appendChild(sp);
lis.appendChild(li);
numOfNewCMs++;
}
function highlight(id){
var element= document.getElementById('sp'+id);
element.style.backgroundColor='white';
element.style.color='brown';
}
function highlight2(id){
var element= document.getElementById('sp'+id);
element.style.backgroundColor='black';
element.style.color='yellow';
}
li{
margin-bottom:20px;
}
li > span{
padding:5px;
margin-bottom:10px;
}
li:hover > span{
color:brown;
background-color:white;
}
<button onclick="generateLi()">Click me</button>
<div id="lis" style="margin-top:20px;"></div>
i am working on this example of appendChild() method.but the difference is here i am trying to add more text to a div dynamically.that was all right.but the hard part is the text i want to add will be red in color.how can i do that?
i tried
text.setAttributes('color',"red");
But it didn't work.so,how this task can be done??please help,thanks!!!!
the full code is given below............
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function create_text(){
var mydiv = document.getElementById("mydiv");
var text = document.createTextNode(" New text to add.");
mydiv.appendChild(text);
}
</script>
</head>
<body>
<button onclick="create_text();">Create Text Node</button>
<div id="mydiv">Welcome, here is some text.</div>
</body>
</html>
You would normally have to use CSS properties, however, text nodes cannot have CSS properties applied to them. You therefore need another container element:
You can choose any container element you wish, e.g. div, span, etc. It just needs to be capable of containing a text node. Having an element then allows us to access the styles property and set various styles (the color attribute in your case).
→ jsFiddle
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
container.style.color = "red";
mydiv.appendChild(container);
}
Further note:
the order of the color assignments and calls of appendChild is arbitrary. The following would also be possible:
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
mydiv.appendChild(container);
container.style.color = "red";
}
mydiv.style.color = 'red';
or just in css
#mydiv { color: red; }
if you have other elements inside the div that you don't want to be red, you'd need to wrap the new text in a span or div or another element before appending.
with jquery this would be super easy:
$('#mydiv').append('<span style="color:red">this is new text</span>');
If that's everything in your div, you could try
document.getElementById("mydiv").style.color="#ff0000";
newNode = document.createElement("span");
newNode.innerHTML = "text";
range.insertNode(newNode);
Is it possible to make the text in innerHTML with red background color? I want to add style="background-color:red" to just created span. Is it possible? Or it must have some id, and then I can change this span with jQuery?
Simple enough:-
newNode.style.backgroundColor = "red";
Better to give a classname for the span
<style>
.spanClass { background-color: red; }
</style>
newNode.className = "spanClass";
This worked for me:
var spanTag1 = document.createElement('span');
spanTag1.innerHTML = '<span style="color:red">text</span>';
OR
add class using js and set css to that class
var spanTag1 = document.createElement('span');
spanTag1.className = "mystyle";
Now set style to that class
<style>
.mystyle {
color:red;
}
</style>
You can add attributes directly to the DOM object. The style attribute can be assigned by this way too. Example:
var span = document.createElement("span");
span.setAttribute("style","color:white;background-color:red;");
var text = document.createTextNode("My text");
span.appendChild(text);
Of course you have to add this element created to their parent object in your page:
var parent = document.getElementById("parentObject");
parent.appendChild(span);
This method "setAttribute()" lets you to add other non-standard attributes used by animations and custom jquery options to your HTML standard tags.