Change class property by using jquery - javascript

I would like to add a property directly to a class instead of objects that have given class.
It should work for dynamically added elements as well.
I tried to do it by using $(".myElement").css("background", "green"); but it works only for already existing elements, the new elements are created with default class properties.
My code is:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<style>
.myElement{
width: 20px;
height: 20px;
background: red;
margin: 5px;
}
</style>
</head>
<body>
<div id="elementsContainer">
<div class="myElement"></div>
<div class="myElement"></div>
</div>
<button id="addClassProperty">Add class property</button>
<button id="addNewElement">Add new element</button>
<script>
$("#addClassProperty").click(function(){
$(".myElement").css("background", "green");
});
$("#addNewElement").click(function(){
$("#elementsContainer").append("<div class='myElement'></div>");
});
</script>
</body>
</html>
The expected result should add a new property to all existing element and to every newly created elements without cast change property for newly created element.
Is there any way to solve this problem?

This is far simpler by adding a class to the parent container and a corresponding css rule for .myElement when that class exists
$("#addClassProperty").click(function() {
$('#elementsContainer').addClass('active')
});
$("#addNewElement").click(function() {
$("#elementsContainer").append("<div class='myElement'></div>");
});
.myElement {
width: 20px;
height: 20px;
background: red;
margin: 5px;
}
.active .myElement {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elementsContainer">
<div class="myElement"></div>
<div class="myElement"></div>
</div>
<button id="addClassProperty">Add class property</button>
<button id="addNewElement">Add new element</button>

Rather than "change class property", you want to change/add a css rule.
EDIT: better link --> Changing a CSS rule-set from Javascript
Or you could have one/multiple classes with existing css and change your objects' classes instead.

When you apply a green background color to elements, the style of the background color is entered into the style attribute. This is how the css() method works. Therefore, each new element has a background color of red, taken from the css.
To solve your problem, you can use the method with adding a class, or change the color of the background rule in the CSS itself. This can be done using cssRules by referring to the document. Like this:
[...document.styleSheets[0].cssRules].find((currentSel) => (currentSel.selectorText = ".myElement")).style.background = "green";
By placing this code inside the click event of the selector #addClassProperty.
$("#addClassProperty").click(function () {
[...document.styleSheets[0].cssRules].find((currentSel) => currentSel.selectorText = ".myElement").style.background = "green";
});
$("#addNewElement").click(function () {
$("#elementsContainer").append("<div class='myElement'></div>");
});
.myElement {
width: 20px;
height: 20px;
background: red;
margin: 5px;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<style></style>
</head>
<body>
<div id="elementsContainer">
<div class="myElement"></div>
<div class="myElement"></div>
</div>
<button id="addClassProperty">Add class property</button>
<button id="addNewElement">Add new element</button>
</body>
</html>

Related

Can we use class on a <style> tag?

The thing is for js purpose I want a particular <style> tag to be removed from my document on an event. So for that, within my knowledge, I have added a class for it and removed on my event, eg:
<style class="custome_for_remove">
.selected_par>td,
.footer-tr>td {
position: relative;
display: table-cell!important
}.....
</style>
<script>
function customeRemove() {
$('.custome_for_remove').remove()
}
</script>
My concern is this HTML standard, is this a proper method.? I couldn't find any questions or answer related to this.
Yes! This totally works and it also seems to be valid syntax. Here's a little demonstration. According to https://validator.w3.org/ having a class in your style tag is considered valid html (you can also use an id if you want).
$("#test").click(() => {
$(".customClass").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style class="customClass">
p {
color: red;
}
</style>
<p>
Test
</p>
<button id="test">
remove
</button>
You can try the below code. It removes CSS perfectly.
function removeJs(){
$(".custome_for_remove").remove();
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<style class="custome_for_remove">
p {
color: red;
cursor: pointer;
}
</style>
<p onclick="removeJs()">
Click here!
</p>

Changing font size of a particular div that is built in run-time

Consider this:
<div>
<div class="h">header</div>
<div class="m">menu</div>
<div class="m">menu</div>
</div>
The h and m classes are built by a tool that I am not permitted to modify.
I would like to change the 'h' font size in this and only this place. All other places that use the 'h' class must keep the same font size.
I was thinking about adding my own class like this:
<div class='myheader'>
<div class="h">header</div>
<div class="m">menu</div>
<div class="m">menu</div>
</div>
and define this in my .css file like this:
.myheader > * {
}
.myheader.h {
font-size:20px;
}
Unfortunately it does not work for it does not 'see' .myheader.h. It applies only style read from .h and .myheader but not both at the same time.
Is there any other way to change the header font size?
Before you say "modify <div class='h'>header</div>" like I need to reiterate - these likes are being created by a tool - in run-time - so I cannot modify them.
PS. I am using angularJS, but I am not allowed to use jQuery calls.
Thank you in advance!
- Greg,
See http://plnkr.co/edit/R0elLsOdcOfsLpHB1NT1 for an example.
I am able to change font size, and that's cool, but when I add change of a color, it spreads down, and I don't want it. I want in this example to change Level 3, and that's it.
looking at this .myheader.h is inccorrect, what you need is .myheader .h
.myheader .h {
font-size: 20px;
color: red;
}
<div class='myheader'>
<div class="h">header</div>
<div class="m">menu</div>
<div class="m">menu</div>
</div>
Next css children elements will inherit certain attributes, of their parents
The div .level4 is inside level3 so it will inherit from its parent (.level3) unless you override this behaviour.
You have the text content Level 3 in .level4 and afterwards a single div with class level4.You can simply override the inherited rule but making the children elements retain their "default" using color:initial
.level3 > * {
color:initial;
}
Snippet below
/* Put your css in here */
.level1 {
font-size: 10px;
}
.level2 {
font-size: 20px;
}
.level3 {
font-size: 30px;
}
.level4 {
font-size: 40px;
}
.changer .level3 {
font-size: 100px;
color: red;
}
.level3 {
border: solid green;
}
.level3>* {
color: initial;
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class='level1, changer'>
Level 1
<div class='level2'>
Level 2
<div class='level3'>
Level 3
<div class='level4'>
Level 4
</div>
</div>
</div>
</div>
</body>
</html>

What does "this" do when used in function brackets?

I have a simple page with three buttons. I wanted to make one function that changes the background color of my page on a click. So i somehow made it work.
I am basically wondering what exactly "this" does when i use it in my changecolor brackets?
I kind of have a feeling what it does but i need more objective knowledge.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Panel</title>
<link rel="stylesheet" type="text/css" href="style.css"></link>
<script src="javascript.js"></script>
</head>
<body>
<h1>THIS IS SOME TEXT</h1>
<h2>This is some more text</h2>
<button class="buttons" id="button1" onclick="changecolor(this)">;P</button>
<button class="buttons" id="button2" onclick="changecolor(this)">;]</button>
<button class="buttons" id="button3" onclick="changecolor(this)">;)</button>
</body>
</html>
My css:
h1{
background-color: blue;
float: left;
}
h2{
color: blue;
float: left;
width:100%;
}
.buttons{
float:left;
margin-right: 10px;
width: 25px;
height: 25px;
}
#button1{
background-color:green;
}
#button2{
background-color:darkgray;
}
#button3{
background-color:blue;
}
My javascript:
function changecolor(clickedButton){
if(clickedButton.id == "button1"){
document.body.style.backgroundColor="lightgreen";
}
if(clickedButton.id =="button2"){
document.body.style.backgroundColor="gray";
}
if(clickedButton.id =="button3"){
document.body.style.backgroundColor="lightblue";
}
}
Thank you in advance!
In JavaScript this always refers to the “owner” of the function we're
executing, or rather, to the object that a function is a method of.
When we define our faithful function doSomething() in a page, its
owner is the page, or rather, the window object (or global object) of
JavaScript. An onclick property, though, is owned by the HTML element
it belongs to.
Via- http://www.quirksmode.org/js/this.html
this references the DOM element the event occurred on.
In this case, inside changecolor(), clickedButton will reference the <button> object that was clicked.
It sends a reference of the clicked element to the javascript function.
this refers to the button element itself.
this is changing your background color for the body of the document. "this" as in this button or object

addClass() function not being applied to an ID

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Working With DOM</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#gold").addClass("highlight");
});
</script>
<style type="text/css">
body{background-color:#FFCC66;}
#wrap
{margin:0 auto;
border:2px solid #CC8320;
height:500px;}
h1{font-style:italic;
color:#A48713; padding-left:10px;}
#gold{width:200px;
background-color:#D49F55;
height:150px; margin:20px; float:left;height:200px}
input{border:1px solid black; width:150px; margin:0 20px;
background-color:#AA9F55; color:#553F00;font-weight:bolder;text-align:center; }
.info{border:1px solid black; width:150px;background-color:#AA9F55; color:#553F00;font-weight:bolder;text-align:center;margin:0 20px; }
.highlight{background-color:green;}
</style>
</head>
<body>
<div id="wrap">
<h1> Learning Web Engineering Online</h1>
<div data-price="399.99" id="gold">
<h3>Gold Member</h3>
<ul class="course">
<li>HTML5</li>
<li>css3</li>
<li>jquery</li>
</ul>
<form>
<input type="button" value="GET PRICE"/>
</form>
</div>
</div>
</body>
I am having problem with the code above that when using jquery i add class highlight to element with id=gold and inspect it in chrome, although the class is being added to the code the style rule mentioned in highlight class doesn't output in browser. the element is being selected but not styled. what am i doing wrong please help someone.
You should use !important to work it:
.highlight{background-color:green !important;}
Note:
Browser uses ID with higher importance than a class name.
change your css to
#gold.highlight{background-color:green;}
You need to change the priority style for .highlight. Just add #gold before the .highlight style
#gold.highlight{background-color:green;}
The problem here is due to the precendence of CSS selectors. An id selector will override a class selector, so you need to either make the class selector more specific (preferred method):
#gold.highlight { background-color: green; }
Example fiddle
Or aleternatively add !important to it:
.highlight { background-color: green !important; }
However the latter can lead to issues when you have competing !important rules, so it's best to avoid it where possible.
highlight gets applied but as there is background-color property defined in ID it will not be overridden by class value.
As mentioned by #cocco you can use #gold.highlight to override it.
Id has greater precision due to conflict resolution, class css is overridden by your #gold id css
change your class
.highlight{background-color:green !important;}

Why isnt my javascript working?

All my code seems to work except my javascript am I doing something wrong?
Thanks Im only a beginner!
I am trying to make the background change when the mouse goes over the 'Tags' tab but it wont do it? What is going on?
HTML:
<html>
<head>
<script language="JavaScript" type="text/javascript">
// This changes color on mouseover, leaves existing color box.
$('.tab-item').mouseover(function() {
$(this).addClass("tab-mouseover");
}).mouseout(function() {
$(this).removeClass("tab-mouseover");
});
// This changes color when clicked, removed old color box.
$('.tab-item').click(function() {
$('.tab-item').removeClass("tab-selected");
$(this).addClass("tab-selected");
});-->
</script>
<link href="arg.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tab-item tab-selected" id="search-box">
Search
</div>
<div class="tab-item" id="tag-box">
Tags
</div>
</body>
</html>
CSS:
.tab-item {
-moz-border-radius: 10px;
border-radius: 10px;
font: 14px helvetica;
color: #000;
height: 20px;
float: left;
margin: 5px 5px 5px 5px;
padding: 5px 5px 5px 5px;
position: relative;
width: 75px;
}
.tab-mouseover {
background: #bdbdbd;
}
.tab-selected {
background: #c0c0c0;
}
Thanks!
James
You're using jQuery but haven't included it.
You also need to put your jquery code into the jquery ready event:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
// This changes color on mouseover, leaves existing color box.
$(function(){
$('.tab-item').mouseover(function() {
$(this).addClass("tab-mouseover");
}).mouseout(function() {
$(this).removeClass("tab-mouseover");
});
// This changes color when clicked, removed old color box.
$('.tab-item').click(function() {
$('.tab-item').removeClass("tab-selected");
$(this).addClass("tab-selected");
});
});
-->
</script>
You haven't added your library (jQuery, I think) as a source here.
Add it like this:
<script src='http://foo.com/bar/library.js'></script>
If you are, indeed using jQuery, you can directly add the following code to make it work:
<script src='http://code.jquery.com/jquery-1.6.4.js'></script>
Note that the above means you are depending on the availability of the jQuery website and not your own.
As per James' comment on this, yes, you can scrap the jQuery completely, but I'd recommend you to learn JavaScript yourself instead of copying code from a website. If you want to change the background color of the field onmouseover, use code like this:
<div onmouseover="this.style.backgroundColor='#bdbdbd';" onmouseout="this.style.backgroundColor='white';">Search</div>
Or
<div onmouseover='this.className="tab-mouseover"' onmouseout='this.className=""'>Search</div>
Or without JavaScript and just simple CSS:
<style>
.tab-mouseover:hover{
background: #bdbdbd;
}
</style>
<div class='tab-mouseover'>Search</div>
I can't answer the latter part, because I don't understand the use of deleting and then adding the same class to an element onclick.
Well, first, you haven't included a link to the jQuery library in your code. As a result, your code won't work, wherever you put it.
Second, since your code is in a script element at the head of the document, it will execute before the body of the document has been rendered. You need to put it in a
$(document).ready(function() {
/*
* Your code here
*/
});
block.
Try this:
$('.tab-item').hover(
function() {
$(this).addClass('tab-mouseover');
},
function() {
$(this).removeClass('tab-mouseover');
}
);
$('.tab-item').click(function() {
$('.tab-selected').removeClass('tab-selected');
$(this).addClass('tab-selected');
});
http://jsfiddle.net/7dDTv/1/

Categories

Resources