Using an empty space in an Active Class - javascript

I got a little help yesterday with a project yesterday that contained the following line of code:
document.getElementById("test").className += " active"
At first I couldn't get it to work because I wasn't adding the empty space before the " active" part. Once I added it the code worked fine.
Why do you need to do this? Is this a JS thing?

The answer of Spencer already explains the reasons behind the space. I just wanted to note, that reading and writing class names can be simplified using classList. For example, just use the following code to add a class:
document.getElementById("test").classList.add("active");
And to remove it, execute:
document.getElementById("test").classList.remove("active");
Also note that you should add the JavaScript shim as defined in the link above to support Internet Explorer 8 and 9.

Because many classes on an element for its class attribute are separated by spaces, you needed to add a space because you have one or more classes already on the element. For example without the space you would have:
class="fooactive" // A single class "fooactive" that doesn't exist
As in it will concatenate the two values rather than reading them as two separate classes. So you need to add a space so the class attribute will read them as separate classes:
class="foo active" // Two classes "foo" and "active"

Related

Select/Apply Styles to specific character with Javascript

When I write code instead of using camelCase or seperate_with_underscore I separate my class names with custom unicode chars. Such as this:
sideNavܢheaderܢtext
So if I have a class with a specific state modifier I will write it like so:
sideNavܢheaderܢtextᆞbold
These are not css selectors this is just my naming convention. Now for my question.
I am using the atom text editor and sometimes I want to be able to hide these special characters. I can use javascript to select things in Atom, but is it possible to use javascript to literally select a single character?
Then I can use that selection to apply a "display:none" style to it?
Like:
var a = document.getElementByChar("a");
a.style.display = "none";
Any help or ideas would be appreciated!
Update: I don't want to actually remove the characters. Just "hide" them from view. The naming convention I use is actually much more complex than this and I use these special characters to define all sorts of patterns in my document.
However sometimes I only care about certain selectors and I want the others to temporarily go away.
If I'm understanding your question correctly, in JavaScript you can:
Get the entire string from the className:
const string = document.querySelector(".sideNavܢheaderܢtext").textContent
Find the location of the character you want to modify. For example:
string.indexOf('a').
Wrap the character with a span (plenty of ways to do that - check out this one).
Add class to span and style with CSS.
I'm not familiar with Atom. Are each of these selectors within dom elements in Atom?
If all of your selectors existed within <span class="selector"> then you could do something like this...
$('span.selector').each(function(elm){
$(elm).text($(elm).text().split('ܢ').join('<b style="display:none;">ܢ</b>'));
});

How to count classnames of dynamically added elements

Is there something I should keep in mind when trying to count ClassNames of dynamically added elements?
For the following description, refer to the link. Upon clicking the "(+)Course" button on any Semester (which are dynamically added), a Course will be appended to the corresponding Semester, with buttons of its own. This works. However, like I have for the Semesters, I have a limit of how many of each element there can be (i.e., 5 Semesters in total, 7 Courses per Semester), but I can't seem to be able to count my Courses.
Each Semester has a unique ClassName for its Courses, which is a concatenation of the Semester's Id and the word "Course", resulting in something like "sem#4Course". This code snippet is how I assemble and count the ClassNames for each Course. Is there something wrong with it? I've attached the rest of my code in the link.
var parentId = $(this).parent().attr('id');
var crsClass = parentId+"Course";
var crsCount = $('.'+crsClass).length;
https://jsfiddle.net/4efzf681/2/
I only started learning JavaScript/JQuery last week, so please bear with me. And I apologize for not separating my code between HTML, CSS and JavaScript. I work in a single file and separate it upon completion, and I've also never used fiddle before. I appreciate any help.
The # character in your class name values sem#1 and sem#1Course are creating a problem for the $() query selector which sees a class .sem and an id #1 or #1Course. It is better not to use the # and . characters in your class names and IDs. Instead use hyphens and underscore characters.
The improved fiddle is here: https://jsfiddle.net/6pdfjbt1/
You are confusing jQuery's selector engine by adding the parents id attribute to your course class name. The classes will inculde #, guess jquery thinks you want to select an element by it's id.
Changed that by doing
var crsClass = parentId.replace("#", "")+"Course";
I fixed your fiddle. Make sure to put your js in the bottom window next time ;).
I also moved the crsCount variable to the bottom to assign the value after the courses have been appended to the DOM.
YOUR FIDDLE
You can get the elements by class name using javascript method getElementsByClassName
var crsCount = document.getElementsByClassName(crsClass).length;

reason for using a period to call a div class and then calling it later you dont use a period? [duplicate]

This question already has answers here:
JavaScript & jQuery and the use of periods
(2 answers)
Closed 7 years ago.
for the sake of sanity, im wondering why when calling a div class in jquery you use a period, for example
var currentSlide = $('.active-slide');
yet when i call it later in an event handler it needs to have no period otherwise it breaks the code
currentSlide.fadeOut(600).removeClass('active-slide');
I was just wondering why there was inconsistency here, thanks in advance.
One is in jQuery selector format (like a CSS query). The prefix of . just means a class name follows (same as in CSS).
The other is just the name of a class to remove, so having a class selector would be both redundant and slower as the code knows it is a class name bveing passed.
It is no different to having
<div class="someclass">
and css of
.someclass{
color: blue;
}
Where you have no problem with the syntax being different :)
.removeClass receives the class name as the parameter, and class names should not have . by convention:
However, . is used for class selectors. In your selector you have to have . to tell jquery that you are trying to select items with certain class: $('.myclassname')
For example, you would use # to tell jquery that you are looking for an element with a certain id: $('#myElementId')
The $('.active-slide') is a pointer to your element. This pointer will see non-period names as the actual name of the element like div, input. The period tells it to work with everything that has that class and # will tell it to look for a specific id. When you call removeClass, you are explicitly removing a class so no need to use the . to say it is a class, as it is implied.

how to change css with jquery and .each?

I have several div with the .item class and want to change the css if the id is 1
</div>
<div class="item" id="0">
</div>
$('.item').each(function(i){
var estatus = $(this).attr('id');
if (estatus == '1')
// change only item with id = 1
});
Just modify your selector...
$('#1').css('whatever', 'yep');
Please see the comments section to see why this works in this scenario, but you're gonna have bad time if selecting it in a stylesheet. I'd recommend using the method in T.J.'s answer, because of jQuery ever switch to funnelling these calls through querySelectorAll(), it will blow up).
My recommendation is to not use id attributes that start with a number.
With CSS, it's awkward to use id values starting with a digit; the simplest thing is to avoid using them.
But with what you have, you can do this:
$(".item[id='1']").css(/*...*/);
Just using #1 as a selector may work in certain select situations provided they don't rely in CSS parsing, but is invalid. If you must have an id value starting with a digit, to use it with a CSS selector, you have to escape it. The escaped version of #1 is #\31, which gets even more awkward when written as a JavaScript string: $("#\\31").css(/*...*/);.
But this works and is in-spec:
$("#\\31").css(/*...*/);
This works in jQuery as of the current version and is not in spec:
$("#1").css(/*...*/);
It could stop working at any time, however, as it's not in-spec, and breaks if you combine it with various things.

JavaScript String .replace method is replacing all my content?

I have successfully implemented finding and replacing some text with something else in the following way:
$(".class").html($(".class").html().replace(/\text\b/g, '<span class="newclass newclass2">new text</span>'));
When I apply this to my element 'class' it finds all the 'text' and replaces with 'new text' and everything relating to the new classes.
However, if I have more than one element on the page with the same class, it replaces all the classes with whatever text is in the first class.
For example, if my first class has the content "Hello everyone", when the script is applied to this class, it works fine. Any subsequent class of the same name is then replaced with "Hello everyone". These also have the function applied in the same way as the first occurrence of that class.
IE, it applies the script, then replicates this in every single class of the same name on the page.
I do not understand why it would do this, and rather renders the function pointless in many ways if it can't be used to change text throughout different sections without setting up new scripts and different classes.
Hopefully there is something simple at work here that I am not aware of, any help would be much appreciated.
Many thanks
Richard
That is the nature of class selectors--the .html(...) will replace the HTML of everything that matches the .class selector.
If you want to replace text in each individual .class element, you can use the .each function. (There are probably jQuerier ways, too.)
$(`.class`).each(function(n, el) {
var myHtml = $(this).html();
myHtml = mungeIt(myHtml);
$(this).html(myHtml);
});
If you want to select only an individual .class element, then you either (a) don't really want to be using classes, but IDs, or (b) need to understand enough of your structure or the context you wish to operate in to select only the targeted DOM element.
(And hope the structure or context doesn't change without a corresponding code update.)
You're specifying a class with the jQuery selector $(".class") That's what the period indicates. jQuery has a ton of selectors to choose from. A list is provided in the documentation here: http://api.jquery.com/category/selectors/
Also, I'd look at http://api.jquery.com/hasClass/ for your problem as you could then use if...then statements to not run into others
Dave is right about needing to use the .each method. We need to loop through each element at a time because .html() will only return the first element when there are multiple matches.
Try:
$('.class').each(function() {
$(this).html($(this).html().replace(/someWord/g,'withAnother'));
});

Categories