Easier to explain with simple code:
$("#element").fadeOut(); // jQuery; works as expected
I want to use .fadeOut() and select element with JS like this:
document.getElementById("element").fadeOut(); // Does not work
How do I make this work and is there any point of doing this (performance wise)?
Any thought is appreciated. Thanks.
You can assign the fadeOut property name to HTMLElement.prototype, and call jQuery's fadeOut from inside it:
// $("#element").fadeOut(); // jQuery; works as expected
HTMLElement.prototype.fadeOut = function(...args) {
$(this).fadeOut(...args);
}
document.getElementById('element').fadeOut();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element">text</div>
That said, overwriting built-in objects like HTMLElement is pretty bad practice and can cause problems - it would be better to just do what you were doing originally, and call .fadeOut on a jQuery object containing the desired element(s).
You can wrap the element in $():
$(document.getElementById("element")).fadeOut();
However, you may find it's easier just to use the jQuery ID selector #:
$('#element').fadeOut();
If you want to use JQuery features, you need to use $() to call the method i.e. fadeout(). See JQuery Selector.
Now that if you want to do it in vanilla JavaScript then check this out.
Related
In console I have:
$(".myCssClass")[0].parentNode
<li><span class="myCssClass">some text</span></li>
I want to add css class for parent span, for tag <li>
I tried like this:
$(".myCssClass")[0].parentNode.addClass("test")
TypeError: undefined is not a function
I use Jquery 1.5.2
addClass is a method of jQuery objects. When you use $(".myCssClass")[0], you have the real element, not the jQuery wrapper.
Then, you can:
Wrap it to a jQuery object again:
$($(".myCssClass")[0].parentNode).addClass("test")
Only work with jQuery objects:
$(".myCssClass").eq(0).parent().addClass("test")
Add class with plain JavaScript (not supported on old browsers):
$(".myCssClass")[0].parentNode.classList.add("test")
Use .parent()
$(".myCssClass").parent().addClass("test")
.addClass() can only be used against jQuery selectors.
Alternative solution (wouldn't recommend this over the top mentioned solution but for the sake of completion)
$(".myCssClass")[0].parentNode is not a jQuery object, to convert into one you need to wrap with $() like this
$($(".myCssClass")[0].parentNode) //jQuery selector
now addClass(), $($(".myCssClass")[0].parentNode).addClass("test")
I am confused about these lines of JQuery:
if ($(ui).hasClass("color1"))
$(ui).removeClass("color1").addClass("color2")
else
$(ui).removeClass("color2").addClass("color1")
in this code.
I know that $(ui) is creating a JQuery instance. I would like to know if
.hasClass is testing the entire DOM tree of the JQuery instance for
any element which has color1 as part of its class attributes.
Also, the docs for
removeClass do not state what
removeClass returns. They do so allegorically with this code:
$("p").removeClass("myClass noClass").addClass("yourClass");
But I would prefer an explicit statement about what removeClass()
returns. Because my second questions is: what is returned by removeClass and how is addClass can making use of it?
It returns the jQuery object. See the documentation of the removeClass function: http://api.jquery.com/removeClass/
And the jQuery object: http://api.jquery.com/Types/#jQuery
Excerpt from the documentation of the jQuery object:
A jQuery object contains a collection of Document Object Model (DOM)
elements that have been created from an HTML string or selected from a
document. Since jQuery methods often use CSS selectors to match
elements from a document, the set of elements in a jQuery object is
often called a set of "matched elements" or "selected elements".
It returns the elements you selected using the query:
$("[some query here]").removeClass("...").text("the text that must be set");
So, adding class1 and removing class2 can be done like bellow:
$("query .class2")
.removeClass("class2")
.addClass("class1");
On the documentation page you can see: Returns: jQuery.
Look at the documentation for removeClass, it tells you Returns: jQuery
Jquery
I am trying to change the inner text on multiple td element which I believe should look something like this although this does not appear to be a jquery object when I am debugging (I could be wrong).
What is the correct way this should be done?
$('.leg-number').each(function () {
this.html('foo');
});
Maybe try this instead:
$('.leg-number').html('foo');
which is a shorter and more efficient way to achieve your goal. It is just asking jQuery to set the inner html of every element with class "leg-number" to "foo" without any explicit iteration. Most of the jQuery methods like .html() can work on sets of elements so you don't really need to use .each() for simple cases like this.
Now on why your version didn't work: Using .each() would work if you wrapped this with the jQuery function $() so you could use the jQuery methods on it:
$('.leg-number').each(function () {
$(this).html('foo');
});
The variable this inside of the .each() callback is a DOM element and you need $(this) to convert it into a jQuery object that wraps this element. See the explanation in the answer by epascarello who explained it before I updated my answer.
Read the docs for each(). this is a DOM Html Element node, not a jQuery object reference. You can either convert it back to jQuery or use innerHTML directly.
$(this).html('foo');
or
this.innerHTML = 'foo';
The docs show using $(this) in the examples.
Change:
this.html('foo');
to:
$(this).html('foo');
You're attempting to use a jQuery method on a non-jQuery object. This of course assumes that your table cells have the class .leg-number.
I need to set the class for an element in my page. With plain JavaScript, I would write something like:
document.getElementById('foo').className = "my_class";
This just sets the class, which is exactly what I want. But I'm using jQuery on my page and so would like to do this in a "jQuery way", since it seems weird to mix the old style and the jQuery style. But jQuery apparently only allows you use addClass() or removeClass(), like so:
$('#foo').addClass("my_class");
The problem is that it merely adds a class to the element, it does not replace the currently existing class. Does this mean I have to keep track of the old class and do a removeClass() first? Is there no way to tell jQuery to replace the current class no matter what it is and just replace it with a new one?
To remove all classes from an element:
$('#foo').removeClass();
Specifying no arguments to removeClass removes all the classes. So your solution would be:
$('#foo').removeClass().addClass('my_class');
Set the class attribute directly using .attr():
$('#foo').attr('class', 'my_class');
You could use the .attr() function like so:
$('#foo').attr('class', 'my_class');
You could use that:
$('#foo').attr('class', 'my_class');
It will replace any class with "my_class"
$('#foo').removeClass().addClass('my_class');
Ah, found the answer just seconds after I posted the question. Apparently my Google skills were insufficient... :-(
At any rate, the answer is in the removeClass() function. So, you can do:
$('#foo').removeClass().addClass("my_class");
Couldn't be simpler.
you can try using .toggleClass()
How can I access any <div> if I don't declare the id attribute. Does DOM create ID itself?
e.g.
<div class="common_class" onmouseover="know_your_div(this)">
</div>
<script type="text/script">
function know_your_div(obj){
/*
Here i want to access the div object not by class because of it's common
for all div
*/
}
</script>
Well, the answer to your question is right there in your code.
The obj parameter that your know_your_div function takes is supplied as this in the onmouseover attribute. Thus, that is your div.
There's not an easy way to get to it in all browsers. Your best bet is to just create an ID on it. Is there a reason you can't?
Short of that, you have to navigate to it using DOM traversal methods, which are horribly unstable if your DOM structure changes at all. Code like:
document.body.childNodes[3].childNodes[2].childNodes[4];
or
document.getElementsByTagName('DIV')[22]; // 23rd DIV in the page
etc...
The answer is in your Question, let me try to help you
<div class="common_class" onmouseover="know_your_div(this)"> </div>
var oldObject = "";
function know_your_div(obj) {
// write ur condition if/ese/while/..
obj.parentNode.do_Something(); OR obj.parentNode.ID/Class/value
oldObject = obj;
}
then I guess you need to specify the ID explicitly alongside the class name..DOM won't create the ID itself...
Then it's time to use the DOM. Maybe you could use things like firstChild, lastChild, nextSibling.. http://de.selfhtml.org/javascript/objekte/node.htm
If you're using a JS library, like MooTools or jQuery, which I reccomend, you'll have a lot of powerful selector magic at your hands (example http://mootools.net/demos/?demo=Slick.Finder).
Why not use JQuery and selectors?
http://api.jquery.com/id-selector/
No, the DOM does not create an ID. You need to add an ID. You can use jQuery to access a div by it's class.