I have to get what are all the CSS styles used in a HTML file using JavaScript.
<html>
<head>
<style type="text/css">
body {
border: 1px solid silver;
}
.mydiv{
color: blue;
}
</style>
</head>
<body>
</body>
</html>
If the above code is my HTML I have to write one JavaScript function inside the head which returns a string like this.
body {
border: 1px solid silver;
}
.mydiv {
color: blue;
}
Is it possible to do?
For inline stylesheets, you can get the content out of the normal DOM like with any other element:
document.getElementsByTagName('style')[0].firstChild.data
For external, linked stylesheets it's more problematic. In modern browsers, you can get the text of every rule (including inline, linked and #imported stylesheets) from the document.styleSheets[].cssRules[].cssText property.
Unfortunately IE does not implement this DOM Level 2 Style/CSS standard, instead using its own subtly different version of the StyleSheet and CSSRule interfaces. So you need some sniff-and-branch code to recreate rules in IE, and the text might not be exactly the same as the original. (In particular, IE will ALL-CAPS your property names and lose whitespace.)
var css= [];
for (var sheeti= 0; sheeti<document.styleSheets.length; sheeti++) {
var sheet= document.styleSheets[sheeti];
var rules= ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
for (var rulei= 0; rulei<rules.length; rulei++) {
var rule= rules[rulei];
if ('cssText' in rule)
css.push(rule.cssText);
else
css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n');
}
}
return css.join('\n');
From Mdn:
const allCSS = [...document.styleSheets]
.map(styleSheet => {
try {
return [...styleSheet.cssRules]
.map(rule => rule.cssText)
.join('');
} catch (e) {
console.log('Access to stylesheet %s is denied. Ignoring...', styleSheet.href);
}
})
.filter(Boolean)
.join('\n');
Here's my solution :
var css = [];
for (var i=0; i<document.styleSheets.length; i++)
{
var sheet = document.styleSheets[i];
var rules = ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
if (rules)
{
css.push('\n/* Stylesheet : '+(sheet.href||'[inline styles]')+' */');
for (var j=0; j<rules.length; j++)
{
var rule = rules[j];
if ('cssText' in rule)
css.push(rule.cssText);
else
css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n');
}
}
}
var cssInline = css.join('\n')+'\n';
In the end, cssInline is a textual list of all the steelsheets of the page and their content.
Example :
/* Stylesheet : http://example.com/cache/css/javascript.css */
.javascript .de1, .javascript .de2 { -webkit-user-select: text; padding: 0px 5px; vertical-align: top; color: rgb(0, 0, 0); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(204, 204, 204); margin: 0px 0px 0px -7px; position: relative; background: rgb(255, 255, 255); }
.javascript { color: rgb(172, 172, 172); }
.javascript .imp { font-weight: bold; color: red; }
/* Stylesheet : http://example.com/i/main_master.css */
html { }
body { color: rgb(24, 24, 24); font-family: 'segoe ui', 'trebuchet MS', 'Lucida Sans Unicode', 'Lucida Sans', sans-serif; font-size: 1em; line-height: 1.5em; margin: 0px; padding: 0px; background: url(http://pastebin.com/i/bg.jpg); }
a { color: rgb(204, 0, 51); text-decoration: none; }
a:hover { color: rgb(153, 153, 153); text-decoration: none; }
.icon24 { height: 24px; vertical-align: middle; width: 24px; margin: 0px 4px 0px 10px; }
#header { border-radius: 0px 0px 6px 6px; color: rgb(255, 255, 255); background-color: rgb(2, 56, 89); }
#super_frame { min-width: 1100px; width: 1200px; margin: 0px auto; }
#monster_frame { -webkit-box-shadow: rgb(204, 204, 204) 0px 0px 10px 5px; box-shadow: rgb(204, 204, 204) 0px 0px 10px 5px; border-radius: 5px; border: 1px solid rgb(204, 204, 204); margin: 0px; background-color: rgb(255, 255, 255); }
#header a { color: rgb(255, 255, 255); }
#menu_2 { height: 290px; }
/* Stylesheet : [inline styles] */
.hidden { display: none; }
Here is my solution:
function getallcss() {
var css = "", //variable to hold all the css that we extract
styletags = document.getElementsByTagName("style");
//loop over all the style tags
for(var i = 0; i < styletags.length; i++)
{
css += styletags[i].innerHTML; //extract the css in the current style tag
}
//loop over all the external stylesheets
for(var i = 0; i < document.styleSheets.length; i++)
{
var currentsheet = document.styleSheets[i];
//loop over all the styling rules in this external stylesheet
for(var e = 0; e , currentsheet.cssRules.length; e++)
{
css += currentsheet.cssRules[e].cssText; //extract all the styling rules
}
}
return css;
}
It is based on #bobince's answer.
It extracts all the css from both the style tags and the external stylesheets.
Related
I am trying to deploy my first javascript application, which is a Chrome extension.
This simply generates random passwords and stores it with the url of current active tab.
App runs fine on local but after deploying it to Chrome, I got this error:
Uncaught TypeError: Cannot read properties of null (reading 'length')
index.js:65 (anonymous function)
I am a beginner, so any kind of criticism about my code is highly appreciated.
Thank you so much.
function render() {
*line65* **if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
Here is the full index.js file:
var characters = [];
for (var i=32; i<127; i++)
characters.push(String.fromCharCode(i));
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '<') {
characters.splice(i, 1);
i--;
}
}
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '>') {
characters.splice(i, 1);
i--;
}
}
let pw1El = document.getElementById("pw1-el")
let pw1 = ""
let passwords = []
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
let links = []
links = JSON.parse(localStorage.getItem("savedLinks"))
render()
document.getElementById("char-count-el").value = 20
document.getElementById("gen-btn").addEventListener("click", function() {
var charCount = document.getElementById("char-count-el").value
pw1 = ""
for(let i = 0; i < charCount; i++) {
let randomIndex = Math.floor(Math.random() * characters.length)
pw1 += (characters[randomIndex])
}
pw1El.textContent = pw1
})
document.getElementById("save-btn").addEventListener("click", function() {
passwords.push(pw1El.innerText)
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
links.push(tabs[0].url)
})
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
function render() {
**if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
document.getElementById("clear-btn").addEventListener("click", function() {
passwords = []
links = []
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
document.getElementById("copy-btn").addEventListener("click", function() {
var input = document.getElementById("pw1-el").textContent;
navigator.clipboard.writeText(input);
alert("Copied Text: " + input);
})
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>Generate a</br>random password</h1>
<p>Never use an unsecure password again.</p>
<hr>
<div>
<label for="char-count-el">Character Count:</label>
<input type="number" id="char-count-el">
<button id="gen-btn"><span>Generate password</span></button>
</div>
<div>
<label>Your Password:</label>
<div class="pw-container">
<span class="password-line" id="pw1-el">...</span>
<button class="side-btn" id="save-btn">SAVE</button>
<button class="side-btn" id="copy-btn">COPY</button>
</div>
</div>
<div id="saved-passwords-container">
<hr>
<label>Saved Passwords:</label>
<div class="pw-container">
<div id="passwords-el">...</div>
<button class="side-btn" id="clear-btn">CLEAR</button>
</div>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
index.css
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
background-color: #ffffff;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
h1::first-line {
color: white;
}
h1 {
color: #00ffaa;
margin-bottom: 5px;
line-height: 1;
}
label {
font-size: 11px;
display: block;
color: #D5D4D8;
margin-top: 10px;
}
input {
height: 38px;
border-radius: 5px;
border: none;
width: 70px;
padding: 0px 10px;
text-align: center;
background-color: #D5D4D8;
margin-right: 20px;
font-size: 14px;
}
.container {
background: #1F2937;
margin: 0;
padding: 10px 30px 40px;
width: 100%;
min-width: 500px;
box-shadow: 0px 10px 30px 10px #2640644b;
display: flex;
flex-direction: column;
}
.pw-container {
display: flex;
border-radius: 5px;
background-color: #3e4f66;
padding: 10px;
margin-top: 10px;
}
.password-line {
color: #00ffaa;
font-size: 16px;
padding: 5px 10px;
margin-top: 0px;
flex-grow: 1;
flex: 1 1 1;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
#passwords-el {
padding-right: 30px;
flex-grow: 1;
flex: 1 1 0;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
.saved-password-line {
color: #D5D4D8;
font-size: 14px;
padding: 10px 15px;
border-bottom: solid 1px #d5d4d814;
border-radius: 5px;
margin-bottom: 10px;
line-height: 0.9;
}
a {
color: #d5d4d872;
text-decoration: underline;
}
.side-btn {
font-size: 12px;
width: 60px;
border: none;
background: none;
color: #D5D4D8;
padding: 5px 10px;
border-radius: 5px;
justify-self: flex-end;
}
.side-btn:hover {
background-color: #ffffff28 ;
}
#gen-btn {
color: #ffffff;
background: #0EBA80;
text-transform: capitalize;
text-align: center;
width: 200px;
height: 40px;
padding: 10px 10px;
border: none;
border-radius: 5px;
margin-bottom: 10px;
margin-top: 10px;
transition: all 0.5s;
box-shadow: 0px 0px 30px 5px #0eba8135
}
#gen-btn:hover {
box-shadow: 0px 0px 30px 10px #0eba8157
}
#gen-btn span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
#gen-btn span:after {
content: '\279c';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
#gen-btn:hover span {
padding-right: 25px;
}
#gen-btn:hover span:after {
opacity: 1;
right: 0;
}
p {
color: #D5D4D8;
margin-top: 0px;
}
hr {
border-width: 1px 0px 0px 0px;
border-color: #95959576;
margin: 15px 0;
}
manifest.json
{
"manifest_version": 3,
"version": "1.0",
"name": "Password Generator",
"action": {
"default_popup": "index.html",
"default_icon": "icon.png"
},
"permissions": [
"tabs"
]
}
I solved it.
I understand that (please correct me if I'm wrong)
if the local storage is empty, it does not return an empty array when parsed.
Apparently, when I do:
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
passwords is no longer an array.
I instead use:
passwords.push(JSON.parse(localStorage.getItem("savedPasswords")))
But that just pushes a nested array inside passwords.
So I added a for loop, and used an if statement to address the initial error:
let locSavedPasswords = localStorage.getItem("savedPasswords")
if(locSavedPasswords !== null) {
for( var i = 0; i < (JSON.parse(locSavedPasswords)).length; i++){
passwords.push(JSON.parse(locSavedPasswords)[i])
}}
Initially, savedPasswords won't exist in localStorage, so localStorage.getItem('savedPasswords') will return null.
You then do JSON.parse(null), which doesn't immediately crash because null is first coerced to a string and becomes 'null' which is then JSON-parsed and turns back to null since the string with contents null is valid JSON.
But you then do .length on it and crash.
The solution is to handle the case where the item is not yet set and handle it like it was a JSON-stringified empty array. You can do so for example using the nullish coalescing operator ??:
let passwords = JSON.parse(localStorage.getItem("savedPasswords") ?? '[]')
Or, you can keep initializing it with [] as you did before but wrap the assignment with the actual value in a condition:
let passwords = []
const json = localStorage.getItem('savedPasswords')
if (json !== null) {
passwords = JSON.parse(json)
}
Personally, what I like to do for structured data in localStorage is something like this, which also handles the case that other things like invalid JSON somehow got stored there (without bricking the application):
let passwords = []
try {
const data = JSON.parse(localStorage.getItem('savedPasswords'))
if (Array.isArray(data)) passwords = data
} catch {}
The following HTML code creates 3 elements, and allows the user to click on them / select them.
const changeColor = (evt) => {
if (evt.currentTarget.classList.contains("is-active")) {
evt.currentTarget.classList.remove("is-active");
} else {
evt.currentTarget.classList.add("is-active");
}
};
const EL_tagger1010_children = document.querySelectorAll(".tagger1010 span");
EL_tagger1010_children.forEach(EL => EL.addEventListener("click", changeColor));
.tagger1010 span {
padding: 6px 10px;
background: #D0E8E4;
border-radius: 18px;
color: #000000;
font-family: Roboto;
font-size: 12px;
margin: 0 4px 8px 0;
font-weight: 500;
display: inline-block;
word-wrap: break-word;
white-space: normal;
cursor: pointer;
user-select: none;
border: 1px solid BBD0CD;
}
.tagger1010 span.is-active {
background-color: #008fde;
color: #ffffff;
}
.tagger1010 span:hover {
background-color: #008fde;
color: #ffffff;
}
<div class="tagger1010">
<span>Google</span>
<span>Microsoft</span>
<span>Facebook</span>
<span>LinkedIn</span>
</div>
<div class="as-console-wrapper"></div>
<div class="as-console"></div>
What I am looking to do is pre-assign spans as "is-active" if the tag is included in a given list.
For example, if you run the above code, and the given list includes "Microsoft" and "LinkedIn" - I would like for "Microsoft" and "LinkedIn" to already be highlighted and have the background-color be #008fde, and the color be #ffffff.
Would anyone know how I could say, "if the text of this span is included in this list, make it have the is-active characteristics"
Checkout here
https://jsfiddle.net/qmx3105s/
<script type="text/javascript">
const changeColor = (evt) => {
if (evt.currentTarget.classList.contains("is-active")){
evt.currentTarget.classList.remove("is-active");
localStorage.removeItem(evt.currentTarget.textContent);
} else {
evt.currentTarget.classList.add("is-active");
localStorage.setItem(evt.currentTarget.textContent,'true');
}
};
const EL_tagger1010_children = document.querySelectorAll(".tagger1010 span");
EL_tagger1010_children.forEach(EL => {
console.log('EL',EL)
if(localStorage.getItem(EL.textContent)){
EL.classList.add("is-active");
}
EL.addEventListener("click", changeColor);
});
</script>
Edited: Search by innerText and Find in Array added.
Original: I highly recommend adding id="X" to your html to make it easier to target the specific tag. Having to rely on the inner text is much more complicated and bad practice.
Then you need an array to hold your IDs and iterate it. Finally we add the .is-active
Here's what that looks like:
const changeColor = (evt) => {
if (evt.currentTarget.classList.contains("is-active")) {
evt.currentTarget.classList.remove("is-active");
} else {
evt.currentTarget.classList.add("is-active");
}
};
const EL_tagger1010_children = document.querySelectorAll(".tagger1010 span");
EL_tagger1010_children.forEach(EL => EL.addEventListener("click", changeColor));
var tag_names = ["Microsoft", "LinkedIn"];
var tags = document.getElementsByTagName("span");
for (var i = 0; i < tags.length; i++) {
if(tag_names.indexOf( tags[i].textContent ) != -1){
tags[i].classList.add('is-active');
}
}
.tagger1010 span {
padding: 6px 10px;
background: #D0E8E4;
border-radius: 18px;
color: #000000;
font-family: Roboto;
font-size: 12px;
margin: 0 4px 8px 0;
font-weight: 500;
display: inline-block;
word-wrap: break-word;
white-space: normal;
cursor: pointer;
user-select: none;
border: 1px solid BBD0CD;
}
.tagger1010 span.is-active {
background-color: #008fde;
color: #ffffff;
}
.tagger1010 span:hover {
background-color: #008fde;
color: #ffffff;
}
<div class="tagger1010">
<span>Google</span>
<span>Microsoft</span>
<span>Facebook</span>
<span>LinkedIn</span>
</div>
<div class="as-console-wrapper"></div>
<div class="as-console"></div>
The code detects a click outside an element and reloads the page. However, anytime a user clicks outside the page it keeps on reloading the page. How can I reload the page once when the user clicks outside the element?
The reason I want to do this is so when a user inputs text into a form and clicks away the other forms can be rendered with the updated contents. It wouldn't be ideal for the user to click outside the element and the page constantly reloading.
document.addEventListener("click", (evt) => {
const flyoutElement = document.getElementById("flyout-example");
let targetElement = evt.target; // clicked element
do {
if (targetElement == flyoutElement) {
// This is a click inside. Do nothing, just return.
document.getElementById("flyout-debug").textContent = "Clicked inside!";
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// This is a click outside.
document.getElementById("flyout-debug").textContent = "Clicked outside!";
location.reload();
});
body {
font-family: "Arial", sans-serif;
}
h6 {
margin: 0;
font-size: .85rem;
font-weight: normal;
color: #999;
}
.flyout {
position: absolute;
top: 50px;
left: 50px;
padding: 1em;
border: 1px solid rgba(16, 152, 173, .3);
background: white;
box-shadow: 0 .1rem .2rem rgba(0, 0, 0, .15);
}
.flyout-title {
font-size: 1em;
margin: 0 0 .5em 0;
}
.flyout-debug {
min-height: 1.5em;
margin: 0 0 .5em 0;
font-size: .8em;
color: #999;
}
.flyout-buttons {
text-align: center;
}
.button {
display: inline-block;
box-sizing: border-box;
margin: 0 .25em;
padding: .5em 1em;
border: .075rem solid rgba(0, 0, 0, .1);
border-radius: .15em;
background-color: #1098ad;
background-image: linear-gradient(rgba(255, 255, 255, .2), rgba(255, 255, 255, 0));
color: white;
text-decoration: none;
font-family: inherit;
font-size: inherit;
line-height: 1;
box-shadow:
0 .075rem .1rem rgba(0, 0, 0, .15),
inset 0 .075rem rgba(255, 255, 255, .3);
}
.button:hover,
.button:focus {
border-color: rgba(0, 0, 0, .5);
background-image: linear-gradient(rgba(255, 255, 255, .1), rgba(0, 0, 0, .1));
}
.button:active {
background-image: linear-gradient(rgba(0, 0, 0, .1), rgba(0, 0, 0, 0));
box-shadow:
inset 0 .075rem .1rem rgba(0, 0, 0, .2);
}
.button-outline {
background-color: transparent;
background-image: none;
border-color: #1098ad;
color: #1098ad;
box-shadow: none;
}
.button-outline:hover,
.button-outline:focus {
background-color: #1098ad;
background-image: none;
color: white;
}
<div class="flyout" id="flyout-example">
<h5 class="flyout-title">This could be a flyout…</h5>
<div class="flyout-debug" id="flyout-debug"></div>
<div class="flyout-buttons">
<button class="button button-outline" type="button">Cancel</button>
<button class="button" type="button">Ok</button>
</div>
</div>
You can use session storage & add a key to maintain if the page was reloaded before.If the key exist in session storage,it mean it was loaded before. If not then add a key a reload it
document.addEventListener("click", (evt) => {
const flyoutElement = document.getElementById("flyout-example");
let targetElement = evt.target; // clicked element
do {
if (targetElement == flyoutElement) {
// This is a click inside. Do nothing, just return.
document.getElementById("flyout-debug").textContent = "Clicked inside!";
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// This is a click outside.
yee = document.getElementById("flyout-debug").textContent = "Clicked outside!";
const getIsFirstClick = sessionStorage.getItem('firstClick'); // change from here
if (!getIsFirstClick) {
sessionStorage.setItem('firstClick', true)
location.reload()
}
});
I'm not sure exactly what you're trying to do, but what I understood is that when you click within an area you don't want to reload, but if you click any outside, reload should happen, correct me if I'm wrong. Here's a script to do it:
document.addEventListener("click", (evt) => {
const flyoutElement = "flyout-example";
const targetElement = evt.target; // clicked element
if (targetElement.id === flyoutElement) {
// This is a click inside. Do nothing, just return.
document.getElementById(flyoutElement).textContent = "Clicked inside!";
} else {
// This is a click outside.
document.getElementById(flyoutElement).textContent = "Clicked outside!";
const isReloaded = localStorage.getItem('reloaded');
if (!isReloaded) {
localStorage.setItem('reloaded', true);
location.reload();
}
}
});
My main goal is to optimize the sass script using javascript, and my plan is to assign different background colors in the nth-child() using for loop.
But I have searched through many tutorials but I can't find any solutions for it.
var mainColors = ["#1D659D", "#B25353", "#A12456", "#919191", "#7a3091"];
var subColors = ["#2C8AD4", "#FF7777", "#D63475", "#707070", "#b146d1"];
function colorPicker() {
for (var i = 0; i < mainColors.length; i++) {
console.log(mainColors[i]);
console.log(subColors[i]);
}
}
.Wrapper {
display: grid;
grid-template-columns: 100%;
h1 {
padding-top: 10px;
padding-bottom: 10px;
font-size: 30px;
}
div {
border-style: solid;
border-width: 0px 5px 0px 0px;
padding-bottom: 50px;
&:nth-child(1) {
background: #1D659D;
border-color: #2C8AD4;
}
&:nth-child(2) {
background: #B25353;
border-color: #FF7777;
}
&:nth-child(3) {
background: #A12456;
border-color: #D63475;
}
&:nth-child(4) {
background: #919191;
border-color: #707070;
}
&:nth-child(5) {
background: #7a3091;
border-color: #b146d1;
}
}
}
If I got it correctly, you are trying to iterated the colors and set the colors, bellow is the code I have added, this should work for you.
EDIT
Thanks for correcting my #try-catch-finally, querySelectorAll() will return array, so for selecting specific elements we should use querySelector().
function colorPicker(){
for(var i = 0; i < mainColors.length; i++){
document.querySelector('div:nth-child('+i+')').style.background = mainColors[i];
document.querySelector('div:nth-child('+i+')').style.borderColor = subColors[i];
}
}
This way you can apply,
var mainColors = ["#1D659D", "#B25353", "#A12456", "#919191", "#7a3091"];
var divs = document.querySelectorAll('div'), i;
for (i = 0; i < divs.length; ++i) {
divs[i].style.background = mainColors[i];
}
div {
border-style: solid;
border-width: 0px 5px 0px 0px;
padding-bottom: 50px;
}
div:nth-child(1) {
background: #1D659D;
border-color: #2C8AD4;
}
div:nth-child(2) {
background: #B25353;
border-color: #FF7777;
}
div:nth-child(3) {
background: #A12456;
border-color: #D63475;
}
div:nth-child(4) {
background: #919191;
border-color: #707070;
}
div:nth-child(5) {
background: #7a3091;
border-color: #b146d1;
}
<div>111</div>
<div>222</div>
<div>333</div>
<div>444</div>
<div>555</div>
Your CSS is not correct.
<div id="er_msg" style="width:200px;" align="center"></div>
I am adding a class to the above div with JavaScript:
function validateForm()
{
var x=document.forms["form1"]["email_id"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
document.getElementById("er_msg").innerHTML="Pls enter a valid E-Mail Address ";
document.getElementById("er_msg").className="alert alert-error";
}else{
document.getElementById("er_msg").innerHTML="Thank you!";
document.getElementById("er_msg").className="alert alert-success";
saveAppdata();
}
}
Ideally I should get a red colored "Pls enter a valid E-Mail Address" and a green "Thank you!", whereas in this case both messages appear in red. The classes are predefined by Twitter Bootstrap.
I tested your javascript function using Twitter bootstraps css classes and it works without a problem.
Here is my jsfiddle code: http://jsfiddle.net/yqRCX/
Here are the css classes:
.alert {
padding: 8px 35px 8px 14px;
margin-bottom: 20px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
background-color: #fcf8e3;
border: 1px solid #fbeed5;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.alert, .alert h4 {
color: #c09853;
}
.alert h4 {
margin: 0;
}
.alert .close {
position: relative;
top: -2px;
right: -21px;
line-height: 20px;
}
.alert-success {
color: #468847;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-success h4 {
color: #468847;
}
.alert-danger, .alert-error {
color: #b94a48;
background-color: #f2dede;
border-color: #eed3d7;
}
.alert-danger h4, .alert-error h4 {
color: #b94a48;
}
So the answer is.. I don't see any problem with the code you have supplied. Your add class works.
If you have other problems please supply more information like what e-mail values you are trying and such.