I am trying to style a paragraph element which I created in JavaScript.
I am developing a simple To do list so I can improve my skill set.
So I created a paragraph element in JavaScript and I am trying to style it using JS.
My HTML:
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>
My JS:
var toDoItems = [];
var i = 1;
document.getElementById("addItem").onclick = function (){
var userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
document.getElementById("item-list").innerHTML += "<p>"+userInput+ "</p>";
}
Using innerHTML in this case (innerHTML+=) is a bad idea. Because per time that you click your button, previous p tags will be replace with new ps.
In first step, add your new todos with a function similar this:
var List=document.getElementById("item-list");
function AddNewTodo(t, styles/*{style1: "value",...}*/){
var todo=document.createElement("p");
todo.innerHTML=t;
for(var s in styles) todo.style[s]=styles[s];
List.appendChild(todo);
}
Real sample:
window.onload=function(){
var List=document.getElementById("item-list");
function AddNewTodo(t, styles/*{style1: "value",...}*/){
var todo=document.createElement("p");
todo.innerHTML=t;
for(var s in styles) todo.style[s]=styles[s];
List.appendChild(todo);
}
document.getElementById("addItem").onclick = function (){
AddNewTodo(prompt("Enter your Todo: "),
{color: "#900", display: "list-item", listStyle: "inside", paddingLeft: "20px"});
}
}
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
But you can use stylesheet instead of inline style. For this, only change your function like this:
window.onload=function(){
var List=document.getElementById("item-list");
function AddNewTodo(t, styles/*{"simple style name": "simmple css value",...}*/){
var s=document.createElement("style");
document.head.appendChild(s);
var sty="";
for(var st in styles) sty+=st+":"+styles[st]+";";
s.sheet.insertRule("#item-list>p{"+sty+"}", 0);
var todo=document.createElement("p");
todo.innerHTML=t;
List.appendChild(todo);
};
document.getElementById("addItem").onclick=function(){
AddNewTodo(
prompt("Enter your Todo:"),
{"background-color": "#f0f0f0", display: "list-item", "list-style": "inside", padding: "15px"}
);
};
};
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
TIP:
in first way, you must pass styles as CamelCase similar js syntax (border-top > borderTop), but in second method, pass them like css syntax (border-top, background-color ,...).
Other way:
you can define style in style tag:
<style type='text/css'>
#item-list>p{
color: #f90;
/*other styles*/
}
</style>
In this case, your function will be similar this:
function AddNewTodo(t){
var todo=document.createElement("p");
todo.innerHTML=t;
List.appendChild(todo);
}
full sample:
window.onload=function(){
var List=document.getElementById("item-list");
function AddNewTodo(t){
var todo=document.createElement("p");
todo.innerHTML=t;
List.appendChild(todo);
}
document.getElementById("addItem").onclick = function (){
AddNewTodo(prompt("Enter your Todo: "));
}
}
#item-list>p{
color: "#900";
display: list-item;
list-style: inside;
padding-left: 20px
}
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
The easiest way to style an element using plain Javascript is as such:
document.getElementById("myDiv").style.borderColor = "red";
First you get the element by the id. You can give an element an id like this: <div id="myDiv"></div>
Then you get the element by using the document.getElementById() function.
And then you can style it using the style object.
But the best way to do it is by still using a stylesheet or to do it dynamically using jQuery.
What you should do is make variable for document.getElementById("item-list") and then add .style.backgroundColor('white'); or you can do
document.getElementById("item-list").style.backgroundColor('white');
Create your classes with set of style formatting you want to do. Then you can use function as example given below:
function addClass() {
var element = document.getElementById("myPara");
element.classList.add("mystyle");
}
function removeClass() {
var element = document.getElementById("myPara");
element.classList.remove("mystyle");
}
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = new style
example : add document.getElementById("item-list").style.color ='red'; this line after toDoItems.push(userInput);
just add a class to the p-element and style it via css
document.getElementById("item-list").innerHTML += '<p class="foo">'+userInput+'</p>';
You can add a class name to p tag and write css for that class This may help yours
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var toDoItems = [];
var i = 1;
document.getElementById("addItem").onclick = function (){
var userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
document.getElementById("item-list").innerHTML += "<p class='className'>"+userInput+ "</p>";
}
});
</script>
<style>
.className {
border:1px solid #ccc;
}
</style>
</head>
<body>
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
</body>
</html>
Thanks i figured it out by adding a class to the paragraph tag.
Related
I have created a simple addition program using HTML, CSS and Javascript.
HTML code is as follows:
<head>
<title>Input Output</title>
<link rel="stylesheet" type="text/css" href="io.css">
<body>
<h1>Sum App</h1>
<div class="container">
<script type="text/javascript" src="io.js"></script>
First Number <input type="text" id="numOne">
Second Number <input type="text" id="numTwo">
<button type="button" class="btn" onclick="submitBut()">Submit</button>
<p id="result"></p>
<div class="screen" id="screen1"></div>
</div >
The Javascript code is as follows:
function submitBut(){
var numOne= document.getElementById("numOne").value;
var numTwo= document.getElementById("numTwo").value;
var sum=parseInt(numOne)+parseInt(numTwo);
var element= document.createElement("p");
document.getElementById("result").innerHTML = sum;
}
I want to now style the result which as per the code seats in between paragraph tags with id "result".
What are the ways using which this is possible?
I tried using a standard style sheet format as below:
#result {
font-size: 45-px;
background-color= Yellow;
}
However, it is not working at all. Kindly let me know possible fixes.
Regards,
The problem is with the CSS you have written for this code. It's Invalid.
Change it like the following and it will work fine:
#result {
font-size: 45px;
background-color: yellow;
}
I have a paragraph tag with a class of "price" which I want to add a span tag inside using either Javascript, Jquery or both.
E.g
BEFORE: <p class="price"></p>
AFTER: <p class="price"><span class="whatever">Sale</span></p>
How can I achieve this?
You can do as follows:
$("p.price").append($(`<span class="whatever">Sale</span>`));
This is plain JavaScript code
function addSpan() {
var price = document.getElementsByClassName('price')[0];
var span = document.createElement('span');
span.classList.add('whatever');
span.innerText = 'Sale';
price.appendChild(span);
}
addSpan();
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p class="price"></p>
</body>
</html>
You can make the method more generic by passing parameters as well.
To add it within the first .price element, without jQuery:
document.querySelector(".price").insertAdjacentHTML(
"beforeend",
"<span class='whatever'></span>"
);
With jQuery:
$(".price").first().append("<span class='whatever'></span>");
If you know there's only one, you can leave out .first().
if need vanilla javascript:
var lcs_els = document.getElementsByClassName('price');
for(var key in lcs_els){
lcs_els[key].innerHTML = '<span class="whatever">Sale</span>';
}
<p class="price"></p>
if need jquery:
$('.price').html('<span class="whatever">Sale</span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="price"></p>
Jquery variant 2 if need manipulate of span:
var span = $('<span/>').attr('class', 'whatever').html('Sale');
$('.price').append(span);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="price"></p>
If you click the button, it should have showed, but it doesn't.
Is any wrong here?
I have written many JavaScript files in this way, and tried many ways like changing the position of JavaScript code anywhere. But all the files I wrote don't work
Thanks in advance!
An instance :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class = "show" onclick = "JavaScript : show();">Show</button>
<script type = "text/JavaScript">
function show() {
document.querySelector("debug").style.display = "flex";
}
</script>
</body>
</html>
Thanks to all of you!
About .querySelector()
The Document method querySelector() returns the first Element within the document that matches the specified selector. [...] The selector is a CSS selector string.
- MDN web docs
You should, therefore, put in your code:
document.querySelector(".debug")
You can also select HTML elements by their tags, for example, you want to select the first div:
document.querySelector("div")
document.querySelector("div").style.color = "lightgreen"
<div>Hello World</div>
Imagine you had your own HTML tag: <hello>, then you can select all hello elements with:
document.querySelector("hello")
document.querySelector("hello").style.color = "lightblue"
<hello>Hello World</hello>
Side note on inline eventListeners
Also in HTML for inline event listener instead of:
<button class = "show" onclick = "JavaScript : show();">Show</button>
you can simply write:
<button class = "show" onclick = "show();">Show</button>
It is recommended to use JavaScript to initiate these eventListeners instead of having them inline inside your HTML markup. Use the .addEventListener() method:
document.querySelector(".show").addEventListener('click', show)
↑ ↑
event function
type
Back to your code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class ="show">Show</button>
<script type = "text/JavaScript">
document.querySelector(".show").addEventListener("click", show)
function show() {
document.querySelector(".debug").style.display = "flex";
}
</script>
</body>
</html>
Last thing
Also it's better to keep HTML, JavaScript and CSS all in separate files, for instance:
- index.html
- style.css
- script.js
And call the CSS and JavaScript files in your HTML file with the link (preferably inside <head>) and script (at the bottom of <body>) tags:
<link rel="stylesheet" type="text/css" href="style.css">
And
<script src="script.js"></script>
For class selector you need to add a dot (.) e.g. .debug
Also, in HTML, you can simply have onclick as onclick="show();"
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="show();">Show</button>
You were not passing class to querySelector. Set ".debug" instead of "debug".
Below is working code:
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="JavaScript : show();">Show</button>
queryselectors requires . and # for class and ID selector:
querySelector(".debug")
I want erase a inline CSS <style> element in a <div> element. This <style> element is output from a JavaScript file.
This is the document:
<div id="rmid" class="rm">
<script type="text/javascript" src="http://domain.com/file.js"></script>
</div>
Loading this JavaScript file creates additional elements (editor's note: presumably via document.write()) , resulting in HTML markup like the following example:
<div id="rmid" class="rm">
<script type="text/javascript" src="http://domain.com/file.js"></script>
<style> ............. </style>
various content
</div>
How can I remove this when loading the page ?
If you are using jquery,
you could use
$(document).ready( function() { $( '#rmid > style' ).remove(); } );
If you plan to not use jQuery, the things changes a little bit:
var parent = document.getElementById("rmid");
parent.querySelector("style").innerHTML = "";
You can call the function <body onload="removeStyles()" This will select all the styles in your above mentioned div with #id = id.
function removeStyles(){
var sty = document.querySelectorAll('div#id style');
for(var i=0; i<sty.length; i++){
sty.item(i).remove();
}
}
I'm trying to get all title out of body text.
I created a button and linked my function to it.
However, when I click on it, it disappears and I want it to stay in the same place because I will add other buttons with other functions.
Do you know any idea how I could keep it always in there?
I tryed to use fixed position but soon realised that it just fixes the button on top if I scroll down for example.
Also, when I get the titles my text is in different shrift, I just wonder why is that?
Your guidance will be appreciated.
This is what I have at the moment:
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#navigation li{
display:inline;
postion:absolute;
}
#navigation a{
padding:2px 2px;
background-color:#09F;
color:#FFFFFF;
}
#navigation a:hover{
background-color:#F90;
color:#666;
}
</style>
<div id="navigation">
<a href="#"><input type=button onclick="myFunction()">
</div>
</head>
<body>
<div>
<p id="demo">
<pre>
<b>This is one title</b>
I'm writing here
the text that I
don't need to get.
<b>Other title</b>
And so we'll test
whether this thing works.
</p>
</pre>
</div>
<script>
function myFunction() {
var text = document.body.innerText;
var titles =text.match(/^\n(.+?)\n\n/mg);
for (var i = 0; i < titles.length; i++) {
document.write(titles[i] + "<br />" + "<br />");
}
}
</script>
</body>
</html>
Basically you have an opening <a> tag but not a closing one. That makes your whole website a link. But apart from that you had a lot of invalid HTML. Closing tags that were mixed up and HTML between </head> and <body>.
Your HTML should look like:
<html>
<head>
<meta charset="utf-8"/>
<title>test</title>
<style>
#navigation li{
display:inline;
postion:absolute;
}
#navigation a{
padding:2px 2px;
background-color:#09F;
color:#FFFFFF;
}
#navigation a:hover{
background-color:#F90;
color:#666;
}
</style>
</head>
<body>
<div id="navigation">
<input type=button onclick="myFunction()" />
</div>
<div>
<p id="demo">
<pre>
<b>This is one title</b>
I'm writing here
the text that I
don't need to get.
<b>Other title</b>
And so we'll test
whether this thing works.
</pre>
</p>
</div>
<script>
function myFunction() {
var text = document.body.innerText;
var titles =text.match(/^\n(.+?)\n\n/mg);
for (var i = 0; i < titles.length; i++) {
document.write(titles[i] + "<br />" + "<br />");
}
}
</script>
</body>
</html>
Here you go. I have fixed the HTML, made it more semantic (by removing the onclick from the HTML), and made the algorithm simpler by using document.getElementsByTagName().
New code:
var r = document.getElementById('results');
document.getElementById('btn').onclick = myFunction;
function myFunction() {
var titles = document.getElementsByTagName('b');
for (var i = 0; i < titles.length; i++) {
r.innerHTML += titles[i].innerHTML + "<br />" + "<br />";
}
}