CSS Not Applied to Node Added by JS appendChild - javascript

My html:
<div id=Info>
<p>Id: <span>001</span></p>
</div>
My CSS:
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
My JS code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue1);
pElement.appendChild(elementValue2);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
CSS style applied correctly to the line:<p>Id: <span>001</span></p> from html file. But somehow, CSS style is not applied to the node added by appendChild from JS file. I couldn't figure out why.
I'm new to html/CSS/JS, any help would be appreciated!
Thanks!

It looks like the div id is not match between your html and the css.
In the html, the id=Info should be id="bookInfo"

Is seems to be qworking perfectly fine, but there are multiple issues in shared code.
CSS is referring to #bookInfo as opposed to #Info
You are appending elementValue1 to spanElement as opposed to elementValue2.
Let's look at fixed code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
<div id=Info>
<p>Id: <span>001</span></p>
</div>

not a good way to do it but here is your code:
https://jsfiddle.net/r6j31zhL/
<html>
<body>
<div id="Info">
<p>Id: <span>001</span></p>
</div>
</body>
</html>
<style>
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
</style>
<script>
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info span').appendChild(pElement);
</script>

Related

add a button using javascript to an existing DIV

On my page I have:
<div id='something'></div>
and I want to append this type of 'button' to it using JS:
<span class="picon-p-add-news"></span>Read more news
I tried to use document.createElement but I'm not sure how to make it not just append it as text. How do I do this ?
Something like this, where you can pass your element ID and URL through function arguments.
<!DOCTYPE html>
<html>
<head>
<script>
function appendButton(elementId, url){
var buttonEl = document.createElement("a");
buttonEl.href = url;
var buttonTextEl = document.createElement("span");
buttonTextEl.className = "picon-p-add-news";
buttonTextEl.innerText = "Read more news";
buttonEl.appendChild(buttonTextEl);
document.getElementById(elementId).appendChild(buttonEl);
}
</script>
</head>
<body>
<div>
<button id="button">Click to add</button>
<div id='something'></div>
</div>
<script>
document.getElementById("button").addEventListener('click', () => appendButton("something", "/news_events/"));
</script>
</body>
</html>
Use document.createElement to create the specified HTML elements. Then you can append those to your #something root element using Node.appendChild function. You can also use Element.innerHTML to gets or sets the HTML markup contained within the element.
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
const something = document.getElementById('something');
// creating the span element, then add a class attribute
const span = document.createElement('span');
span.setAttribute('class', 'picon-p-add-news');
span.innerHTML = 'span'; // some text to improve visualization
// create the anchor element with the href attribute
const a = document.createElement('a');
a.setAttribute('href', '/news_events/');
// append the span element inside the <a>
a.appendChild(span);
a.innerHTML += 'anchor'; // add extra text for display
// add the <a> element tree into the div#something
something.appendChild(a);
#something {
border: 1px solid;
text-align: center;
font-size: 2rem;
}
#something > a {
padding: 8px;
}
.picon-p-add-news {
background: red;
padding: 0 4px;
}
<div id="something"></div>
Like this? You can use the innerHTML attribute to add HTML inside of an Element
document.getElementById("something").innerHTML += '<span class="picon-p-add-news"></span>Read more news';
<div id='something'></div>
Or, if you created this as an Element with createElement, you can use appendChild:
let a = document.createElement("a");
a.setAttribute("href", "/news_events/");
let span = document.createElement("span");
span.setAttribute("class", "picon-p-add-news");
a.appendChild(span);
a.innerHTML += "Read more news";
document.getElementById("something2").appendChild(a);
<div id="something2"></div>
1) Create a element:
var aEl = document.createElement('a');
aEl.href = "/news_events/"
2) Create span element:
var spanEl = document.createElement('span');
spanEl.classList.add('picon-p-add-news');
3) Append span element to a element
aEl.appendChild(spanEl);
4) Insert text in a element
aEl.insertAdjacentText('beforeend','Read more news');
5) Append whole a tree to you div
var divEl = document.getElementById('something');
divEl.appendChild(aEl);
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to create a P element with some text, and append it to DIV.</p>
<div id="myDIV">
A DIV element
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var para = document.createElement("P");
var t = document.createTextNode("This is a paragraph.");
para.appendChild(t);
document.getElementById("myDIV").appendChild(para);
}
</script>
</body>
</html>
Give something like this a try: I used https://www.w3schools.com/jsref/met_document_createelement.asp for reference.

How do I check if a letter is bold?

I'm trying to change all bold characters to italic ones and vica versa. I figured out I need to iterate through the entire document.
So far I defined the two styles and a part of the function, not sure if the styles are needed.
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<script>
function swap() {
if (fontWeight == 'bold') {
fontWeight == 'normal';
fontStyle == 'italic';
}
elseif (fontStyle == 'italic') {
fontStyle == 'normal';
fontWeight == 'bold';
}
</script>
Well, you could do this with querySelectorAll, considering only swapping .bold and .italic depending on their current class:
function swapCollection( collection, from, to ) {
if ( !collection ) {
return;
}
for( let i = 0; i < collection.length; ++i ) {
const elm = collection[ i ];
elm.classList.remove( from );
elm.classList.add( to );
}
}
function swap() {
const allBold = document.querySelectorAll( '.bold' );
const allItalic = document.querySelectorAll( '.italic' );
swapCollection( allBold, 'bold', 'italic' );
swapCollection( allItalic, 'italic', 'bold' );
}
document.getElementById( 'swap' ).addEventListener( 'click', swap );
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<div>
<span class="bold">Hello</span> <span class="italic">world!</span>
</div>
<button id="swap">swap</button>
You can also use getElementsByClassName to choose class and change style then:
function swap() {
var mass=document.getElementsByClassName("bold");
for (i in mass){
mass[i].style.fontWeight="normal";
}
}
it's not useful to add a JS script for something that can be done once and for all.
so try to overwrite the default style of strong and em tags inyour CSS files by adding the following CSS code
strong, b{ font-weight: normal!important; font-style: italic!important; }
em, i{font-style: normal!important; font-weight: bold!important; }
then replace all properties in your CSS files
font-style: italic; by font-weight: bold;
and
font-weight: bold; by font-style: italic;
using your IDE
This is a generalize solution, using jQuery, not based only on class names.
I do the bolded texts red so you can see it easily.
$('div').each(function () {
if ($(this).css('font-weight') == 'bold') {
$(this).css('color', 'red'); // but you change to italic
return;
}
if ($(this).css('font-style') == 'italic') {
$(this).css('color', 'green'); // but you change to bold
return;
}
});
.one, .three {font-weight: bold;}
.five {font-style: italic;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">aaa</div>
<div>ccc</div>
<div class="three">ddd</div>
<div>eee</div>
<div style="font-weight: bold;">lala</div>
<div style="font-style: italic;">tata</div>
<div>nana</div>
<div class="five">dada</div>
If you want to apply something to a text which is both bold and italic, remove the returns in the if blocks.
If it is simply a matter of toggling the classes, you could do it like this. Each time you click the button it will change the bold text to italic and vice versa.
const
trigger = document.getElementById('trigger');
function toggleClasses() {
const
// Get all the elements with the bold and/or italic class.
elements = document.querySelectorAll('.bold, .italic');
// Iterate over all the elements
elements.forEach(element => {
// For each element, toggle the bold and italic classes.
element.classList.toggle('bold');
element.classList.toggle('italic');
});
}
trigger.addEventListener('click', toggleClasses);
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<p class="bold">initally bold</p>
<p class="bold">initally bold</p>
<p class="italic">initally italic</p>
<p class="bold">initally bold</p>
<p class="italic">initially italic</p>
<button id="trigger" type="button">toggle classes</button>
You may simply collect all items with .bold and .italic classes under a node list with document.querySelectorAll(".bold, .italic") and toggle their classLists.
var sps = document.querySelectorAll(".bold, .italic"),
mbt = document.getElementById("mbt");
mbt.addEventListener("click", _ => sps.forEach(function(sp){
sp.classList.toggle("bold");
sp.classList.toggle("italic");
}));
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<p><span class="bold">Hello</span> <span class="italic">World</span></p>
<button id="mbt">Toggle</button>

How to format a text in a div with jQuery/Css

I would like to display a text copied from a site, for example Wikipedia, in a div. This text has to be strictly without the tags that the computer copies with the text from wikipedia.
I think that the solution is to set a sort of formatting of the text but I don't know.
This is how it should be (Press OK). But I don't want to paste the text in the code, I have to paste the text in the textarea.
In fact if you try to paste something from Wikipedia in the textarea of this Jsfiddle you will see that the result is horrible and with all the html tags.
HTML:
<div id="faketxt" contenteditable></div>
<button id='btn'>OK</button>
<button class="fontStyle" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"><b>B</b>
</button>
<button class="fontStyle" onclick="document.execCommand( 'underline',false,null);"><u>U</u>
</button> <br>
<div id='boxes'>
</div>
CSS:
#faketxt {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
.fakes{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
display:inline-block;
float: left;
}
#boxes{
display : flex;
display:inline-block;
}
jQuery:
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = 130;
var words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);
if (words.length) {
var count = 0;
var div = createDiv();
var bold = false;
words.forEach(function(word) {
if (++count > wordLimit) {
count = 1;
div = createDiv();
}
if (div.innerHTML) {
div.append(' ');
}
if (word.indexOf('<b>') != -1) {
bold = true;
}
if (bold) {
$(div).html($(div).html() + '<b>' +
word + '</b>');
} else {
$(div).html($(div).html() +
word);
}
if (word.indexOf('</b>') != -1) {
bold = false;
}
});
}
});
function createDiv() {
div = document.createElement('div');
div.className = 'fakes';
document.getElementById('boxes').append(div);
return div;
}
innerHTML or jquery's $.html() will pull the content (including HTML) of an element. But textContent or jquery's $.text() will just get the text.
Instead of var words = primo.innerHTML have you tried using var words = primo.textContent or var words = $(primo).text()?
try using
words = primo.textContent.replace(/(<^>]+)>)/ig,"").split(/\s/);
instead of
words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);
Rather than getting the innerHTML of the source, simply get the text content using either the javascript or JQuery text() functions.
So, given you are using jQuery, change your words variable to initialise as follows.
var words = $(primo).text().split(/\s/);

Is there a limitation when applying the style via the class attribute in javascript?

I am trying to create a label via javascript but the css does not seem to be applied.
Example code (tested in Chrome):
<html>
<head>
<style type="text/css">
#wrapper {
width:700px;
}
#form_groups .label {
float:left;
clear:left;
width:180px;
margin-right:3px;
margin-top:2px;
background-color:red;
}
#the_id {
background-color: #FBEF99;
font-family:"Lucida Console", Monaco, monospace;
font-size: .9em;
width: 300px;
margin-top: 2px;
}
</style>
</head>
<body>
<input type="submit" value="Create" onclick="createForm()"/>
<div id="wrapper">
<form id="form_groups" action="">
<label class="label">Id</label>
<input id="the_id" type="text" value="1">
</form>
</div>
<script type="text/javascript">
function createForm () {
var wrapper = document.getElementById('wrapper');
var form = document.getElementById('form_groups');
wrapper.removeChild(form);
form = document.createElement('form');
form.id='form_groups';
var lbl = document.createElement('label');
lbl.textContent = 'Name';
lbl.class = 'label';
var name = document.createElement('input');
name.type = 'text';
name.id='the_id';
form.appendChild(lbl);
form.appendChild(name);
wrapper.appendChild(form);
}
</script>
</body>
</html>
The text gets the css but the label does not when I press the button Create.
Is there a limitation when assigning a style using class attribute dynamically via javascript?
You should be using className and not class.
lbl.className = 'label';
Modern Day browsers support classList
lbl.classList.add("label");

Changing HTML id via JS

I hava a script that consist of "hello world" and the "hello" and "world" are in two different CSS styles.
I would like to click onto either of them and they would swap their styles. Example is I click on "hello" and it would swap style with "world". Below is my codes.
I couldn't get it to swap. How should I correct it ?
<html>
<head>
<style>
#today{
font-weight: bold;
color: red;
}
#normal{
font-weight: normal;
color: green;
}
</style>
<script>
old="old";
function set(in){
var e = document.getElementsByName(old);
for(ii=0;ii<e.length; ii++)
{
var obj = document.getElementsByName(old).item(ii);
obj.id="normal";
}
old=in;
var e = document.getElementsByName(old);
for(ii=0;ii<e.length; ii++)
{
var obj = document.getElementsByName(old).item(ii);
obj.id="today";
}
}
</script>
</head>
<body>
<table>
<tr>
<td id="normal" name="new" onclick="set('new')">Hello</td>
<td id="today" name="old" onclick="set('old')">World</td>
</tr>
</table>
</body>
</html>
At any time, only one element can be annotated with an ID. Therefore, you should use classes instead of IDs to annotate your elements. Also, make sure to include a doctype.
Live demo of the corrected code:
<!DOCTYPE html>
<html>
<head>
<style>
.today{
font-weight: bold;
color: red;
}
.normal{
font-weight: normal;
color: green;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
var els = document.querySelectorAll('.normal,.today');
for (var i = 0;i < els.length;i++) {
els[i].addEventListener('click', function () {
var els = document.querySelectorAll('.normal,.today');
for (var i = 0;i < els.length;i++) {
var currentClass = els[i].getAttribute('class');
var newClass = currentClass == 'today' ? 'normal' : 'today';
els[i].setAttribute('class', newClass);
}
}, false);
}
}, false);
</script>
</head>
<body>
<table>
<tr>
<td class="normal">Hello</td>
<td class="today">World</td>
</tr>
</table>
</body>
</html>
Of course, it's way easier to write with jQuery (demo):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script>
$(function() {
$('.normal,.today').click(function() {
$('.normal,.today').each(function(i, el) {
var $el = $(el);
if ($el.hasClass('today')) {
$el.removeClass('today');
$el.addClass('normal');
} else {
$el.removeClass('normal');
$el.addClass('today');
}
});
});
});
</script>
You have a few problems here. First, in your onclick handler, it has to be "javascript:set" instead of just "set". Second, you have a parameter named "in" which is a Javascript keyword. Change all references of it to "inv". If you do that, your code will sort-of work. Try it.
Beyond that, I suggest that you work in Firefox, and get the Firebug add-in, so that you can open the console. It will show you these kinds of errors.

Categories

Resources