I have a site that creates new divs in real time (using JS).
The class of each div is "conv".
My problem is, that the css rules that I have written for this class doesn't apply to the new divs.
conv.length is the length of the xml file I am using.
The JS:
for(i=0; i<conv.length;i++){
var div= document.createElement("div");
div.id="conv"+i;
div.class= "conv";
div.innerHTML=conv[i].childNodes[0].nodeValue;
div.style.height="50px";
div.style.overflow="hidden";
document.getElementById("conv").appendChild(div);
}
The CSS:
.conv {
background-color:#CCC;
}
The class property of an HTML element is a special case, it is not the class attribute. That one is accessible via className:
div.className="conv";
Related
So:
I just tried to use loops to add a background color and a border to each element in class .readtrue or .readfalse, but then somehow the last element, even though it changed class like the others, did not change the border or background color.
Then I tried to add something in Javascript that would just add <style> </style> element to <head> </head>, but according to a console error the <head> </head> element does not exist, although checking the information about the page this item exists.
Then I just tried to change the properties of these classes in a separate CSS file, but it had no effect.
That's why I'm here. I'm a Javascript beginner and have no idea how to change the background color so that the browser will say it's worth showing.
if (val.read === true) {
div.setAttribute('class', 'readtrue')
} else {
div.setAttribute('class', 'readfalse')
}
val is an object with the 'read' attribute and depending on whether 'read' is true or false, div class should change.
I am not sure how you are getting the variable div but a simple example for what you want to achieve is as follows.
I have commented the code, if you need more clarity, kindly comment on this answer.
function toggleBackgroundColors() {
// Fetch all the elements which has 'element' as a class
var spans = document.getElementsByClassName("element");
// Loop through all the fetched elements
for(var i =0 ; i < spans.length;i++) {
var element = spans[i]; // assign a single element
// Check if the element already has a 'bgColor' class
if(element.className.includes("bgColor","")) {
// If it does, simply remove it
element.className = element.className.replace("bgColor","");
}
else {
// If it does not, simply add it
element.className += " bgColor";
}
}
}
/* basic styling for the element */
.element {
width:20px;
height:20px;
display:inline-block;
border:1px solid #000;
background-color:blue;
}
/* color class you want to add */
.bgColor {
background-color:red;
}
<div>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
</div>
<button onclick="toggleBackgroundColors()">toggle color</button>
I just tried to use loops to add a background color and a border to each element in class .readtrue or .readfalse, but then somehow the last element, even though it changed class like the others, did not change the border or background color.
It's possible you have another styling overriding your class's style on the last element. Bootstrap and css pseudo-classes like :hover are the usual culprits. Use your browser developer tools and append your class's style with !important, like so background-color: yourColor !important; to test it out.
You could also be adding both classes
Then I tried to add something in Javascript that would just add element to , but according to a console error the element does not exist, although checking the information about the page this item exists.
The correct way to query an element by tag name is document.querySelector("head") or $("head") in jQuery, but jQuery returns a jQuery Object so you dereference it by doing [0]
BUT
Using JavaScript to append a <style> element to the <head> section of your page is horrible practice. Please just add the styling through a reference to a style sheet on the actual HTML.
HTML
<h1>Changing the Style</h1>
<p>JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="openMe()">Open!</button>
<button type="button" onclick="closeMe()">Close!</button>
<p id="demo">Extra details...You can open and close this paragraph using the buttons above.</p>
CSS
.close {
display: none;
}
.open {
display: block;
}
button {
width:150px;
background-color: #00CCEE;
margin-left:15px;
font-size:120%;
}
#demo {
color:white;
background-color: #7F7F7F;
padding:10px;
font-size:120%
}
JAVASCRIPT
function closeMe(){
x=document.getElementById("demo");
x.className="close";
}
function openMe(){
x=document.getElementById("demo");
x.className="open";
}
Can I use Like x.IdName= "close"; In Javascript?
So far I know there are two ways to change style attributes using Javascript.
x = document.getElementById("demo");
directly eg.. (x.style.backgroundColor ="red";
by Class name eg.. (x.className="abc";)
for using class name we do use:
x = document.getElementById("demo");
x.className="abc";
My questions:
Can I use Id to change style attributes insted of useing className? if yes Please show.
Can I call "x" {x=document.getElementById("demo");} a variable?
There are three ways to modify the style of an element with JavaScript:
Modify the inline style. This is represented by the .style property on the element and the style attribute on the HTML tag.
Modify any feature of the element so that selectors on rulesets in the stylesheet start and or stop matching it. e.g. .foo { ... } would match elements that are members of the foo class, so if you modify the .className property to add or remove an element from that class, you will change the rules that apply to it. You can change other factors such as the id (not usually a logical idea), arbitrary attributes, or anything else that a selector exists for.
Modify the rulesets in the stylesheet itself.
You've already modified the style attribute of the element in your example.
x.style.backgroundColor= "red";
This is what modifying the style attribute is. The second example you edit the elements class name. I'm assuming what you mean is if you can apply styles to elements, using ids?
If that's the case, you can style elements by using the class selector which looks like this
.className {
/* Some styles */
}
Or with the id selector
#demo {
/* Other styles */
}
The two examples above either need to go into their own stylesheet, or inside the HTML in a <style></style> element.
document.getElementById selects element having certain ID. When You want to select elements by a classname, you can use i.e. document.querySelector('.your-class') to select nodes containing your-class className.
When You write
x = document.getElementById("demo");
x.style.backgroundColor ="red"
You are setting style using Id to select a node.
In the line x = document.getElementById("demo");x is the variable.
After running this line, the value of this variable is set to whatever function document.getElementById("demo"); returns. In this case, it's pointing to DOM element with Id attribute "demo".
The css
div.online:last-child {
color:green;
}
div.offline:last-child {
color:green;
}
JavaScipt
var x=navigator.onLine;
var div = document.createElement("div");
if (x==false) {
var divContent = document.createTextNode("sorry, you're offline");
divContent.className="offline:last-child";
div.appendChild(divContent);
var k = document.body.appendChild(div);
} else {
var divContent = document.createTextNode("you are online");
divContent.className="online:last-child";
div.appendChild(divContent);
var k = document.body.appendChild(div);
}
here I am using .className to change the style of last word using the last-child pseudo class (so only offline and online are styled). I'm guessing there is a problem with the naming of the class in my js code.
Before I took this approach I used setAttribute, but I had little idea how to go about using pseudo classes using that. What class name (and / or code) should I be using?
First, you can't assign a class to a text node, only to an element. Assign the online or offline class to the div, not its text content.
Second, you can't directly assign a pseudo-class like :last-child. Selectors with such a pseudo-class in CSS are used to target elements that are the last child of their parent in the DOM tree.
I have appended a textbox to a div area. However I want it to goto a new line in that div after it does that, so my for loop prints a column of textboxes instead of a row.
I tried this:
<div id="timearea"> </div>
var br = '<br/>';
br.appendTo("#timearea");
However this does not work. What would the code be?
You would need to create the element using the createElement() method then append the child to the element using the appendChild() method
var br = document.createElement("br");
document.getElementById("timearea").appendChild(br);
I suggest you apply CSS styling to your divs to control how they are laid out. You can add attributes to style inline or (preferably) add classes to assign styles via JavaScript.
The display attribute controls the flow - display:block should do it.
.my_block_class {
display:block;
}
You can then add the class with JavaScript like so:
document.getElementById("timearea").className += "my_block_class";
Or, if you want to do it without classes:
document.getElementById("timearea").style.display = "block";
Not sure if you mean textarea or input type="text" but regardless, it is better to do this in CSS. In your CSS file or inline style description add:
#timearea input {
display:block;
}
If it's an input element you are adding, or:
#timearea textarea {
display:block;
}
If it's a textarea.
I have the following line of code
document.getElementById("divName").style.display = "none";
How do I hide a bunch of layers at once with totally different names without writing the line of code that often?
Thanks
Felix's thoughts are good. There's a third way: Since they all share a common ancestor (body), you can hide them by adding a class to body and having rules in the CSS that match the actual elements in question, like so:
body.foo table {
display: none;
}
That would hide every table on a page if you added the class "foo" to body, like this:
document.body.className += " foo";
...and then show the tables again if you removed it:
document.body.className =
document.body.className.replace(/\bfoo\b/, '');
Live example
Naturally, that selector can be a lot more discerning:
body.foo div.magic > table {
display: none;
}
That would only hide table elements that were immediate children of a div with the class "magic" (and only when body had the class "foo").
Off-topic: If the approach above doesn't suit (and it doesn't suit a lot of situations), JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others can make manipulating sets of elements (in the ways that Felix mentioned) dramatically easier than going it alone.
Option 1 -- Create a function
function hideDiv(divname) {
document.getElementById(divname).style.display = "none";
}
Option 2 -- Hide a parent element
If all of the elements can be put inside of a parent element or already are, you can simply hide that parent element.
Option 3 -- Use a framework
A javascript framework like jQuery or MooTools will have a convenient coding convention such as .hide()
jQuery: -- see http://api.jquery.com/hide/
mooTools -- see http://mootools.net/docs/more/Element/Element.Shortcuts
Also, frameworks have tools for more complex situations and will allow you to select children of elements or a particular class and iterate through them. They can come in very handy when working with a page that has dynamically created content.
`
// jQuery Example 1: class-hiding
$(".elementsToHide").hide()
// jQuery Example 2: hiding divs within element "#whatever"
$("div", "#whatever").each(function() {
$(this).hide();
});
If they all have the same parent/ancestor, hide the parent (if possible).
Get the references to that elements, put them into an array and loop over them.
var divsToHide = ["thisDiv", "thatDiv", "divName"];
for (var i=0; i<divsToHide.length; ++i)
{
var div = document.getElementById(divsToHide[i]);
if (div) div.style.display = "none";
}
Or, you could use a framework like jQuery, and give the hidden divs some attribute in common, like a class of "hidden". Then,
$(".hidden").hide();
Course, in that case, you could also just set display: none on the class via CSS.
If they are from the same class you could select all elements of that class and loop through them. If they are all of the same parent you can select all the children, loop through them, filter if necessary and hide them this way.
var names = ['divName1', 'divName2','divName3'];
for ( i in names ) document.getElementById(names[i]).style.display = "none";