Changing the Style Attributes in javascript use className - javascript

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

Related

Why doesn't CSS properties work properly with Javascript?

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.

How to show hidden pseudo-element with JavaScript

I'm using CSS to hide form elements:
#main_form #form-field-email, #form-field-realtor_select { display: none;}
#main_form .elementor-select-wrapper::before { display: none; }
Then JavaScript to show them with:
document.getElementById("form-field-first_name").onclick = function(){
document.getElementById('form-field-email').style.display = 'block';
document.getElementById('form-field-realtor_select').style.display = 'block';
The problem is with the pseudo-element .elementor-select-wrapper::before which is needed to hide the down arrow in the select element. I need to get the arrow to display using the JavaScript onclick event. I tried document.getElementsByClassName() but that did not work.
You can see the test page here: Test Page. Click First Name or Last Name to reveal fields (more than listed above) and you'll see the down arrow is mission from the select element.
So, it's not possible to select a pseudo element directly, but you can create a set of CSS styles like the following, which will change the ::before element using a "toggleable" class on the parent:
#main_form .elementor-select-wrapper::before {
display: none;
}
#main_form .elementor-select-wrapper.show-chevron::before {
display: block;
}
When you add (or remove) the .show-chevron class to .elementor-select-wrapper, it should toggle the ::before element.
document.getElementsByClassName('elementor-select-wrapper')[0].classList.add('show-chevron')
Let me know if this works! If not, I can take another look

How to use Javascript to add multiple style properties to one element?

I've tried various renditions of this code to try and change a certain element for a coding exercise but non of them seems to be able to change multiple styling properties of an element on a button click. Would love some assistance. Thanks!
document.getElementById("Combo Style").onclick = function() {
document.getElementById ("More Text").style.fontSize.color = "50px , #BB65C5";
}
You can use cssText property but it will change the styling for the element completely
Style cssText Property
document.getElementById("myP").style.cssText = "background-color:pink;font-size:55px;border:2px dashed green;color:white;"
This will overwrite the existing css styling for that element , so make sure you included every needed property.
To achieve your expected result use setAttribute
HTML:
<button id="Combo Style">Change</button>
<div id="More Text">abcd</div>
JS:
document.getElementById("Combo Style").onclick = function() {
document.getElementById("More Text").setAttribute("style", "font-size:50px;color:red;");
}
http://codepen.io/nagasai/pen/AXVWwO
You need to grab the element by using id or any selector and use style property or css text property to apply css. Check the below code -
var element=document.getElementById("More Text");
element.style.fontSize="20px";
element.style.color="red";
element.style.background="blue";
You can also use cssText property, like -
document.getElementById("More Text").style.cssText='fontSize="20px";color="red";'
This will insert an inline style tag in the element with the csstext property.

How do I create a new line in JavaScript?

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.

alter divs css with javascript

Can I change style of some div link. Here is what I mean
<div id="somediv">something/div>
Lets say I have css like this :
#somediv a{
color:#000;
}
Now for instance upon some action such as mouse click on any element I want to change somediv a link css to
#somediv a{
color:#00ffff;
}
I know how to select div, by using Document.get.elementById('somediv') Is it possible to select a by using above method or any other?
Thank you
DETAILS: Yes I know how to select it using jquery, or prototype .. I can't use any of those..
If you just want to apply a style to a particular element, it's very easy to do:
document.getElementById('whatever').style.color = '#f0f';
If you actually want to apply cascading styles (eg: #someDiv a), then it's not so easy (though it is definitely possible). I would suggest applying a new class to something, and having a pre-existing rule in your CSS.
CSS:
#someDiv a {
color: #000;
}
#someDiv.awesome a {
color: #f0f;
}
Javascript:
document.getElementById('someDiv').className = "awesome";
Yep, you can modify the actual CSS rules at runtime. See Totally Pwn CSS with Javascript for more details.
If you're using jQuery or YUI, there's some good info in question 1079237
document.getElementById ( 'somediv' ).children[0].style.color = 'new color';
assuming the A tag will be the first element inside your DIV
You could use CSS behaviors for this:
For instance:
#somediv a:hover
{
color:#0ff;
}
Otherwise, you may create a dedicated class (used when an element is click for example):
#onclickclass
{
color:#0ff;
}
Then in JavaScript, on onClick event, do:
document.getElementById('somediv').className = 'onclickclass';
And to change the style use
document.getElementById('somediv').className = 'your-css-class';
If you really want to select the anchor you would have to then traverse the document.getElementById('somediv').children array.
As others have suggested though the simpler answer would be to set the className attribute on your div and let the CSS style cascade onto the anchor tag.

Categories

Resources