how check whether style has appended or not - javascript

Here is my code,
<!DOCTYPE html>
<html>
<head>
<style>
.class1 {
color:red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>
I need to check whether class1 has used or appended in style tag in jquery? how it's possible..

I am guessing you want to find if the style is provided within the style tag. Just get all the style tags - and see if the class is within the tags
var found_class = false;
$('style').each(function() {
if ($(this).html().indexOf('.class1') > -1) {
found_class = true;
return false;
}
});

I don't know if this can be easily done with jQuery, but here's a 'vanilla' JavaScript way to do it...
Stylesheets have a cssRules property that contains a list of its rules, ordered by the index in which they appear in the stylesheet. So basically, you can 'loop' through the rules and try to find one that matches your search.
The function:
function ruleExists(sheetId, selector) {
var styleSheet = document.getElementById(sheetId);
if(!styleSheet || styleSheet.tagName !== 'STYLE') return false;
styleSheet = styleSheet.sheet.cssRules;
for (var i = styleSheet.length; i--;) {
if(styleSheet[i].selectorText === selector) return true;
}
return false;
}
So just add an id to your stylesheet (I find it more convenient than using document.styleSheets, but you can modify the function to use that instead), and pass the stylesheet's id and desired rule selector to the function. (Of course, if you are using ids, this will only work for inline stylesheets). Here's an example:
Your stylesheet:
<style type="text/css" id="styleShizz">
.class1 {
color: red;
}
</style>
Your JavaScript:
ruleExists('styleShizz', '.class1'); // true
ruleExists('styleShizz', '.class2'); // false
Here's an example JSFiddle:
http://jsfiddle.net/kfubnwx2/5/

JSBIN
you can use have .hasClass() to inspect it in jquery. The method return true or false about whether contain class what you want.

Try this:
if ($(".class1")[0]){
//exists
} else {
// Do something if class does not exist
}

Related

How do i change the color of an appended string?

I've a div
<div class="display-container"></div>
Inside this div i want to append some text using a JavaScript event listener
const calculatorDisplay = document.querySelector(".display-container")
function appendNumber(number) {
calculatorDisplay.append(number)
}
// number event listener
one.addEventListener("click", () => {
calculatorDisplay.append(1)
})
it work perfecly, but the problem here is that the background color of the display-container div is black, and the default color for string is black, so, how do i change the color of an appended string?
i've already tried using the style tag, but that does not work, i've tried using fontcolor() too, but that too doesn't worked.
I've noticed that the appended string have an id of #text, but i cannout use it if i try.
Define css class
<style>
.colored-text {
color: red;
}
</style>
And then create span element with colored-text class and append it
// number event listener
one.addEventListener("click", () => {
const newSpan = document.createElement('span');
newSpan.classList.add('colored-text');
newSpan.textContent = 1;
calculatorDisplay.append(newSpan);
})
BTW. why are you defining appendNumber function and not using it?
There are several ways to achieve this.
javascript
const calculatorDisplay = document.querySelector(".display-container")
// changing the color to red
calculatroDisplay.style.color = 'red';
// it accepts also Hex colors
calculatorDisplay.style.color = '#FF5733'
// OR rgb
calculatorDisplay.style.color = 'rgb(255,0,0)
CSS
It is also possible to append a classname to your div. Like this you could
make the code probably more reusable and may apply more styles than just colors in a simple manner. (There are multiple ways to include CSS in your html, google it^^ )
// within in the <head> tag in the html add a <style> tag.
<html>
<head>
<style>
.red-color {
color: red
}
</style>
</head>
<body>
<!-- ..... --->
</body>
</html>
In the code you can now add a classname using element.classList.add() OR element.classList.remove() to remove classes!
function setRedColor(el) {
el.classList.add('red-color')
}
function removeRedColor(el) {
el.classList.remove('red-color')
}
const calculatorDisplay = document.querySelector(".display-container")
setRedColor(calculatorDisplay)
// ...
removeRedColor(calculatorDisplay)
Note that the element.classList API generally does not allow classnames with a whitespace in it. So if you have mutliple classes you have to apply them one by one or you'll run into an error.
Feel free to leave a comment

Changing properties of all <hr> html elements

In css I have set all the <hr> elements in my html to "display:none;" which works.
I have an onclick event listener set up to change the "display" to "block".
I use:
document.getElementsByTagName("hr").innerHTML.style.display = "block";
I get an error "Cannot read property 'style' of undefined".
Do it the following way:
var hrItems = document.getElementsByTagName("hr");
for(var i = 0; i < hrItems.length; i++) {
hrItems[i].style.display = 'block';
}
This is incorrect in two ways
getElementsByTagName gives you a list on elements and there is no method to operate on all elements, so you'll have to loop through all of them and add the required style individually.
innerHTML returns a string containing the mark up in an element but <hr> doesn't have any thing in it and the style property is on the <hr> itself.
var hrs = document.getElementsByTagName("hr");
for(var i = 0; i < hrs.length; i++) {
hrs[i].style.display = 'block';
}
Simple (and very effective) solution:
tag your body with a class-element
<body class="no_hr"> <article><hr/> TEXT Foo</article> <hr/> </body>
in css don't hide hr directly, but do
.no_hr hr {
display:none;
}
now define a second style in your css
.block_hr hr{
display:block;
}
in your buttons onClick, change the one and only body class from no_hr to block_hr
onclick() {
if ( document.body.className == "no_hr" ) {
document.body.className = "block_hr";
} else {
document.body.className = "no_hr";
}
}
This is a very charming solution, because you don't have to iterate over elements yourself, but let your browsers optimized procedures do their job.
For people who want a solution that doesn't require JavaScript.
Create an invisible checkbox at the top of the document and make sure that people can click on it.
<input type="checkbox" id="ruler"/>
<label for="ruler">Click to show or hide the rules</label>
Then tell the stylesheet that the <hr>s should be hidden by default, but should be visible if the checkbox is checked.
#ruler, hr {display:none}
#ruler:checked ~ hr {display:block}
Done. See fiddle.
getElementsByTagName() returns a node list, and therefore you must iterate through all the results. Additionally, there is no innerHTML property of an <hr> tag, and the style must be set directly on the tag.
I like writing these types of iterations using Array.forEach() and call:
[].forEach.call(document.getElementsByTagName("hr"), function(item) {
item.style.display = "block";
});
Or, make it even easier on yourself and use jQuery:
$("hr").show();

why the color of the label doesn't change?

After the page loads the color of the label (which is "enter your name") should change to red.But the color of the label remains the same.Why is this so ?
SCRIPT
window.onload = startScript;
function startScript() {
if( document.getElementById("text_field").value === "me") {
var allTags = document.getElementsByTagName("label");
allTags.className = "inserter";
}
}
HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="inserter.js">
</script>
<style type="text/css">
#import url("inserter.css");
</style>
</head>
<body bgcolor="#99FFFF">
<form>
<label>Enter your name<input type="text" id="text_field" value="me" />
</label>
</form>
</body>
</html>
CSS
#charset "utf-8";
/* CSS Document */
.inserter {
color:#F00;
}
Now since the value is equal to me class name "inserter" is dynamically inserted to the label element and the color should appear to be red.
Why doesn't this happen ?
I think you need to loop through allTags:
var allTags = document.getElementsByTagName("label");
for (var i = 0; i < allTags.length; i++) {
allTags[i].className = 'inserter';
}
If you can though use jQuery, it makes life so much easier!
UPDATE to add jQuery equivalent of your code:
if ($('#text_field').val() === 'me') {
$('label').addClass('inserter');
}
It's just so much tidier
The getElementsByTagName method returns an array containing each of the DOM elements that match that tag. Calling allTags.className = 'inserter' assigns a value to the 'className' property of the array itself, not to each of the elements within that array. You'll need to iterate through it, and assign the className to each tag individually.
As others have already mentioned getElementsByTagName() returns an array with elements but also you should add brackets to the first row where you call startScript() to identify it as a function.
This example works; http://jsfiddle.net/aQASU/
Try this through jquery.
allTags.addClass("inserter");

change div/link class onclick with js - problems

Figured out how to change the class of a div/link/whatever onclick with JS. Here's a quick demo: http://nerdi.net/classchangetest.html
Now what I'm trying to figure out is how I can revert the previously clicked link to it's old class (or "deactivate") when clicking a new link.
Any ideas? Thanks!
function changeCssClass(navlink)
{
var links=document.getElementsByTagName('a');
for(var i=0, n=links.length; i<n; i++)
{
links[i].className='redText';
}
document.getElementById(navlink).className = 'blueText';
}
With this code all links will be red and lust clicked will be blue.
I hope it will be helpfull.
function changeCssClass(ele, add_class) {
// if add_class is not passed, revert
// to old className (if present)
if (typeof add_class == 'undefined') {
ele.className = typeof ele._prevClassName != 'undefined' ? ele._prevClassName : '';
} else {
ele._prevClassName = ele.className || '';
ele.className = add_class;
}
}
Try it here: http://jsfiddle.net/Zn7BL/
Use it:
// add "withClass"
changeCssClass(document.getElementById('test'), 'withClass');
// revert to original
changeCssClass(document.getElementById('test'));
It is a much better to post your code here, it makes it easier for those reading the question and for others searching later. Linked examples are unreliable and likely won't persist for long.
Copying from the link (and formatting for posting):
<style type="text/css">
.redText, .blueText { font-family: Arial; }
.redText { color : red; }
.blueText { color : blue; }
</style>
<script language="javascript" type="text/javascript">
The language attribute has been deprecated for a very long time, it should not be used. The type attribute is required, so keep that.
function changeCssClass(navlink)
The HTML class attribute is not sepecifically for CSS, it is used to group elements. A better name might be changeClassName.
{
if(document.getElementById(navlink).className=='redText')
{
document.getElementById(navlink).className = 'blueText';
}
else
{
document.getElementById(navlink).className = 'redText';
}
}
</script>
Link 1<br><br>
When called, the function associated with an inline listener will have its this keyword set to the element, so you can call the function as:
<a ... onclick="changeCssClass(this);" ...>
Then you don't have to pass the ID and you don't need getElementById in the function.
You might consider a function that "toggles" the class: adding it if it's not present, or removed if it is. You'll need to write some small functions like hasClass, addClass and removeClass, then your listener can be:
function toggleClass(el, className) {
if (hasClass(el, className) {
removeClass(el, className);
} else {
addClass(el, className);
}
}
Then give your links a default style using a style rule (i.e. apply the redText style to all links), then just add and remove the blueText class.
You might also consider putting a single function on a parent of the links to handle clicks from A elements — i.e. event delegation.

jquery get styles from an id

does anyone know how can i get all styles applied to an id using jquery (so i can reuse it later in another tag)? something like
css:
div#myid{
width:100px;
height:100px;}
so i can later do something like:
for (var parts in $('#myid').css())
alert ('all parts of the style' + parts);
$('#myid').attr('class') returns a string of the classes.
You should be able to figure it out from here.
var classes = $('#myid').attr('class').split(' ');
for(var c in classes)
{
alert(classes[c]);
}
It is not jquery but works well:
var style = window.getComputedStyle(document.getElementById('myid'), null);
alert(style.color);
You can replace document.getElementById('myid') by $('#myid').get(0) if you really want to use jquery here.
This works either for a style given by CSS or directly applied on the element with the style attribute.
Not sure.. I had tried attr('class') before and it returned empty. trying now again produces the same result (nearly). i suppose attr('class') in jquery isnt exactly the same as styles defined via id. try running this, let me know if you get different results please:
<html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
alert($('#myid').attr('class')); // returns 'empty'
var classes = $('#myid').attr('class').split(' ');
for(var c in classes){
alert(c); // returns 0
}
});
</script>
<style>
#myid {
width:100px;
height:100px;
background:red;
}
</style>
<body>
<div id="myid"></div>
</body>
</html>

Categories