addClass() function not being applied to an ID - javascript

<!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;}

Related

Change class property by using jquery

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>

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>

is it possible to add class to a pseudo element?

I guess not as this is not working:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" >
$("p:after").addClass("allgone");
</script>
<style type="text/css">
p:after {
content: "daniel";
}
.allgone{
display: none;
}
</style>
<title></title>
</head>
<body>
<p></p>
</body>
</html>
JSFIDDLE
No, but you can add the class to the p element, and create an alternate style for it.
p:after {
content: "daniel";
}
p.allgone:after {
display: none;
}
$('p').addClass('allgone');
http://jsfiddle.net/xGUaY/
No, pseudo elements are not part of the DOM, and they can not be accessed via JavaScript.
I believe they are part of the Shadow DOM. The pseudo element is rendered by the browser as an inline element inside of the containing element, either as the first or last child.
No Since they are pseudo elements and not an actual DOM .
But you can do play with the class added, like say if you added the class box
then you can do .box:after and .box:before or .box::after and .box::before depending on the version you are coding.

jquery addClass adding subclass not working

this is my 1st time posting here, so thanks to everyone who can give me some advice!
<html>
<head>
<style>
</style>
<script src="jquery-1.5.2.js"></script>
</head>
<body>
<div
class="super"
style="
border: solid black 1px;
height:100px;
width:100px;
">
</div>
<div
class="super .eight"
style="
background: blue;
">
</div>
<script>
$(".super").click(function () {
$(this).addClass(" .eight");
});
</script>
</body>
</html>
So basically the problem is that I want to add for example a background or some other type of element onto class that is already defined as super. I am trying to use subclasses but it does not seem to be working.
Please ask me if there is anything unclear, I apologize if there is.
No dot (in the classname).
$(".super").click(function () { $(this).addClass("eight"); });
$(".super").click(function () { $(this).addClass("eight"); });

jQuery hover and class selector

I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript.
HTML:
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
CSS:
.menuItem{
display:inline;
height:30px;
width:100px;
background-color:#000;
}
Javascript:
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
EDIT: I forgot to say that I had reasons not to want to use the css way.
And I indeed forgot to check if the DOM was loaded.
Your code looks fine to me.
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
$(function() {
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.
You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.
.menuItem
{
display: inline;
background-color: #000;
/* width and height should not work on inline elements */
/* if this works, your browser is doing the rendering */
/* in quirks mode which will not be compatible with */
/* other browsers - but this will not work on touch mobile devices like android */
}
.menuItem a:hover
{
background-color:#F00;
}
This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)
HTML:
<div id="menu">
<a class="menuItem" href=#>Bla</a>
<a class="menuItem" href=#>Bla</a>
<a class="menuItem" href=#>Bla</a>
</div>
CSS:
.menuItem{
height:30px;
width:100px;
background-color:#000;
}
.menuItem:hover {
background-color:#F00;
}
test.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>jQuery Test</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
</body>
</html>
test.css
.menuItem
{
display: inline;
height: 30px;
width: 100px;
background-color: #000;
}
test.js
$( function(){
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
Works :-)
Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:
HTML:
<ul id="menu">
<li>Bla</li>
<li>Bla</li>
<li>Bla</li>
</ul>
CSS:
#menu {
margin: 0;
}
#menu li {
float: left;
list-style: none;
margin: 0;
}
#menu li a {
display: block;
line-height:30px;
width:100px;
background-color:#000;
}
#menu li a:hover {
background-color:#F00;
}
On a side note this is more efficient:
$(".menuItem").hover(function(){
this.style.backgroundColor = "#F00";
}, function() {
this.style.backgroundColor = "#000";
});
I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.
Don't forget to add display: block ; in .menuItem, so height and width are taken into account.
edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")
If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:
I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...
function changeAttr(attrName,changeThis,toThis){
var mysheet=document.styleSheets[1], targetrule;
var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;
for (i=0; i<myrules.length; i++){
if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){ //find "a:hover" rule
targetrule=myrules[i];
break;
}
}
switch(changeThis)
{
case "height":
targetrule.style.height=toThis+"px";
break;
case "width":
targetrule.style.width=toThis+"px";
break;
}
}
I just coded up an example in jQuery on how to create div overlays over radio buttons to create a compact, interactive but simple color selector plug-in for jQuery
http://blarnee.com/wp/jquery-colour-selector-plug-in-with-support-for-graceful-degradation/
Always keep things easy and simple by creating a class
.bcolor{ background:#F00; }
THEN USE THE addClass() & removeClass() to finish it up

Categories

Resources