Jquery function when calling CSS & HTML - javascript

I am confused regarding the use of ' ' and '.' in a jQuery function.
When exactly do you use one or the other?
For example,
var main = function(){
$('.article').click(function(){
$('.article').removeClass('current')
$('.description').hide();
$(this).addClass('current');
$(this).children('.description').show();
}
)};
$(document).ready(main);
Why is it correct to use .addClass('current') and not .addClass('.current'),
or children('.description') instead of children('description')?
Thank you, I couldn't really find the answer or knew how to look for it on Google.

The . is when you are referring to a Class. Check this for more about classes. So in your case you are using . when you are doing something with the classes. Example $(this).children('.description').show();. Somewhere in your HTML code there is an element with class .description ( example <div class="description"> </div>). And you didn't use . in .addClass() method because you are not referring to existing class but you are "creating" one.
You should also check this to know more about jQuery selectors..

Here is my explanation. There are a couple of different things going on.
This is a typical jQuery pattern:
$(selector).doSomething(parameter);
Whatever is inside $( ) is called the selector. This is an expression that identifies which DOM elements will be selected to apply a function on.
Selectors can have the following format:
'div' or 'a' or ... // selects all the divs or all the anchor tags
'.someclass' // selects all elements that have class 'someclass'
'#someid' // selects all the elements that have id 'someid'
somevariable // a variable that is defined somewhere else (e.g. var somevariable = '.someclass')
The . notation denotes classes. So .description, signifies: Select a class. Which class? The class with the name description.
So much for selectors, now let's look at parameter. A parameter is a variable that you pass to a function. If your function expects a css class, as addClass does, then you pass the name of that class as a parameter. In your case, the name of the class is description.

You would use the prefix . if you are referring to a class, and # if you are referring to an ID.
However, addClass() knows that it is a class, so it does not need the . prefix.

I would like to share my knowledge about your question.
addClass() use to add specific(es) class to current element. It's require class name => You don't need use . before class name.
children() use to get children element, it's require a selector. Selector can be class (.), ID (#) or DOM object (ex div, p, ...).
Read jQuery API documentation for detail
http://api.jquery.com/

jQuery uses CSS selectors to select elements, so when you have a function like children(), you must use a correct css selector, such as '.class-name'. addClass just takes class name as an argument, so 'class-name' is proper one in this case.

Related

JQuery get all nodes of ID and Class

I have this element:
and I want to hide every child of this.
So far I tried this:
var children = $('#OpenLayers.Layer.Markers_41').children();
children.each(function(){
$(this).css('visibility','hidden');
});
But I can not get the specific element with this.
How do I do this?
. in a selector is used to specify a class. If you have . in the ID, you need to escape it so it will be treated literally.
var children = $('#OpenLayers\\.Layer\\.Markers_41').children();
For this reason, it's a bad idea to use characters that have special meaning in CSS selectors (#, ., and :) in IDs and classes.
It's also not necessary to use .each(). jQuery update methods automatically map over all the elements in a collection.
$('#OpenLayers\\.Layer\\.Markers_41 > *').css('visibility', 'hidden');

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.

When to use the css element/class selector in javascript?

I'm currently working on the codecademy course on building an interactive website and I stumbled upon an ambiguity concerning the use of the elemement/class selection of the css elements.
javascript:
var main = function() {
$('.article').click(function() {
$('.article').removeClass('current');
$('.description').hide();
$(this).addClass('current');
$(this).children('.description').show();
});
};
css:
.current .item {
background: rgba(206,220,206,.9);
}
Why do I have to use the element selector 'current' instead of the class selector '.current' in line 4? Is there any rule behind it or just a specification of jquery?
Simply because the name of the class is current not .current, and in
$('.article').removeClass('current');
current is not any selector but just a classname which you want to remove, instead the selector is .article.
You are thinking that we are using element selector instead of class selector. But you are wrong. Do you see the word Class in removeClass and addClass ? It means you are passing class selector, not element selector as an argument.
Now you may ask why don't you see dot with current? Because classes are specified using dot. Actually we have already specified that we are passing Class Selector, as you can see word "Class" in removeClass and addClass .
as per docs addClass():
Adds the specified class(es) to each of the set of matched elements.
Hence, you need to pass the classname/names as parameter and not class selector built out of it.
In addClass/removeClass you use a class name (like the one you'd specify in the class attribute of your html), not a DOM selector like in $().
The function name removeClass() implies you have to state a class name. Using a selector you have to specify either you want to select a class or an ID.
The addClass and removeClass methods accept one or more space-separated classes to be removed from the class attribute of each matched element. The name of the calss you want to add/remove is "current", not ".current"
http://api.jquery.com/removeclass/
http://api.jquery.com/addclass/
In line 4, you are not using 'current' as a selector, it is a class name. Whenever you use some class name as a selector( for example in .find('.current'), $('.current') , closest('.current') etc) then only the rule of putting.for class name#` for id etc are used. And whenever you are checking some class exists( .hasClass()), adding and removing a class(addClass('current'), removeClass('current'),then you have to mention correct class name. I hope it helps.

How to getElementByID in a specific DIV block (JS or JQUery)

I just wanted a fast/easy/simple way to check for existing ID on a specific element (div in this case)..
Can't seem to find code sample for this..im using jquery but i dont think i need to do jquery on this one, just basic getElement.. but i need to isolate the search inside a div block.. because the id does exist in other elements on the page but i need to know if it exist in a specific area/div.
so instead of just
document.getElementById(target_id);
i need something like:
divName.getElementById(target_id);
or
$("document.divName").getElementById(target_id);
or
$(".divName").document.getElementById(target_id);
Can't seem to find something that works.
IDs are supposed to be unique and no two elements in page should have same id. You may search some element with some class in div with specific ID.
$('#divId .someClass')
or using find()
$('#divId').find('.someClass')
or using context, jQuery( selector [, context ] )
$('.someClass', $('#divId'))
var mySubDiv = myParentDiv.querySelector("#mySubDivId")
is equivalent to
var mySubDiv = document.querySelector("#myParentDivId #mySubDivId");
// don't forget the space : #myParentDiv#mySubDivId won't work
where querySelector and querySelectorAll are very useful functions, enough for me to avoid using jQuery : they accept any css selector
in real life, using the same Id for different DOM elements often happens.
id's should be unique, you can check for element using:
$(".your_parent_div").find("div#some_unique_id");
you can use it for the getElementsByTagName or ClassName, but ID is unique over document. so doesn't need to do that. better to use a special ID.
and in every id define as a element in javascript and you can just write id's name and use it, like this :
ID.style.color = red;
According to my understanding on your question, You have used two id's with same name when u execute, It takes only first ID so you are asking to take id from the specific div, well that is bad type of coding to use two id for same name instead go for class if want to use same name.
solution for your question is -this ->
var someDiv = document.getElementsByClassName("divName");
var someId = someDiv[0].getElementById("target_id");

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