add color dynamically to added text - javascript

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";

Related

Creating text node and adding CSS

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

How to edit text style with Javascript

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>

text/template inside js-file?

I want to move this code from my html-file to a js-file, is there any smooth way to do this without having to put the HTML-code as a string?
<script type="text/template" id="template_test">
<h4>Test</h4>
<p>blablabla</p>
</script>
Thanks!
You can use the createElement function to create HTML elements however if you intend to move alot of code you should consider using a templeting engine.
// Create the <h4> element
var heading = document.createElement("h4");
// add the text
heading.textContent = "TEST";
// Create the text node <p>
var p = document.createTextNode("blablabla");
//get the element to which you want to append the h4 and p
var container = document.getElementById("myID");
// Append h4 and p
container.appendChild(heading);
container.appendChild(p);

appendChild is not a function - what am I doing wrong?

I know this is a very common error, but I just can't figure out why this isn't working.
I want to change the value of a span dynamically. Simple, right? I've tried $span.innerHTML = "text" and $span.innerText = "text", which do nothing, but don't throw any errors. My most recent attempt looks like this:
var $resourceSpan = $("#divname"+dynamic_variable);
var stringVar = functionThatReturnsString();
while( $resourceSpan.firstChild ) {
$resourceSpan.removeChild( $resourceSpan.firstChild );
}
var textNode = document.createTextNode(stringVar);
$resourceSpan.appendChild( textNode );
Does anyone know why I'm throwing this error? Thanks
You are dealing with jQuery object, methods like removeChild() and appendChild() belongs to dom element not to the jQuery object.
To remove all contents of an element you can use .empty() and to set the text content of an element you can use .text(), but using .text() will replace existing content so in your case you can just use
var $resourceSpan = $("#divname" + dynamic_variable);
var stringVar = functionThatReturnsString();
$resourceSpan.text(stringVar);
Did you wanna do somethin like this?
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>HI, IM SOME TEXT</span>
<input type = 'button' value = 'Click me!' onClick = 'changeText()'></input> <!-- Change the text with a button for example... -->
<script>
var text = 'I AM THE NEW TEXT'; // The text to go in the span element
function changeText(){
var span = document.querySelector('span');
span.innerHTML = text;
}
</script>
</body>
</html>

JavaScript: how to change CSS style of created span?

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.

Categories

Resources