jQuery version of simple javascript doesnt work - javascript

I have this code in javascript
var greet;
greet = function() {
var textoNombre;
textoNombre = document.getElementById("textoNombre");
return alert(textoNombre.value);
};
what is working on the HTML document. But if I change document.getElementById("textoNombre") by the jQuery version $("#textoNombre") it just dont work. The alert says "undefined".
I have the jQuery script linked on the head of the HTML before to my custom js file.
This is a very basic question but I tried different things and no one work, can you help me please? Thank you in advance.

That's because jQuery objects don't have a value property, the equivelant is $('#someId').val().
To get the underlying DOM object, you can use $('#someId')[0]. This is because jQuery objects are actually like arrays, and their elements are the DOM objects themselves. That means $('#someId')[0].value would work as you'd expect.

jQuery objects are not DOM objects and don't share all their properties.
To get the current value of a form control, you would use the .val() method, not the .value property.

Related

Why can't you call outerHTML on $(this)?

When you want to get the HTML of an entire DOM element (wrapper included), you can do the following (as explained here):
$('#myElementId')[0].outerHTML
But what you can't do is call outerHTML on $(this) inside e.g. a click listener or selector function body scope:
$(this).outerHTML //Doesn't complete in IntelliSense, returns undefined in browser
or
$(this)[0].outerHTML //Correction, this DOES work, but it doesn't complete in IntelliSense
because IntelliSense won't show innerHTML or outerHTML in those circumstances, although with vanilla JavaScript you can do:
document.getElementById($(this).attr('id')).outerHTML
So... what's up with that?
outerHTML is a DOM property; jQuery doesn't expose all DOM properties.
If you have a jQuery object, you can only directly access those properties and methods that jQuery exposes, and vice versa for DOM objects.
In object-oriented terms, jQuery objects don't inherit from DOM objects, they contain them.
Saying $x[0] gets you the DOM object for the first element represented by a jQuery object.
You can use directly this to access outerHTML of the current object instead of indirectly going through $(this) as this represents the DOM object (which has outerHTML property) whereas $(this) represents jQuery object.
this.outerHTML
jQuery selector returns an array-like jQuery object which has no outerHTML property.
However, the jQuery resulting array contains DOM elements.
It means that you can actually access it this way.
$(".someClass")[0].outerHTML // it works for me
Update:
It works for me in every browser.
I can access array-like jQuery object in a click event handler as well.
$(".someClass").click(function()
{
alert($(this)[0].outerHTML); // it works me too
});
Here is my JSFiddle: http://jsfiddle.net/13btf60p/
Update 2:
OK, now I get your question. It should have worked.
Do you really need an IntelliSense to complete such a plain and simple construction?
I will add what I found to be the correct solution to what ended up being a simple flaw in the default Visual Studio settings for future reference.
Since I didn't want to let this go, I searched further and found out that, by default, jQuery IntelliSense is somewhat deplorable out of the box in Visual Studio 2013.
Under
Tools > Options > Text Editor > Javascript > IntelliSense > References
I set
Reference Group: "Implicit (Web)"
and added an existing jQuery file. This solved all issues of my question and IntelliSense now suggests all members and methods correctly, although this should have simply worked out of the box instead of costing everyone a bunch of time.
this.outerHTML is enough.
If you use getElementById maybe you can use:
var table = document.getElementById('blablabla');

how would i implement something like jquerys .data() in pure javascript?

A project I am working on for works wants a pure JavaScript version of the .data() implementation of jQuery.
I wanted to replicate this.
I did a search and Where is jQuery.data() stored? shows where in jQuery it is stored.
I was hoping that i could just attach a datasegment to an HTML element for accessing later.
Since jQuery is Javascript, I can look there, but it makes use of the jQuery objects, which is what I am trying to abstract. I figured there was some sort of way to associate a hash table like dataset with JavaScript and attach it to an object.
http://jsfiddle.net/npXQx/
shows you can create a .data in the object and then it is preserved. You can access it twice, and the data is there.
This example shows a simple string assignment and a function and it being called multiple times.
var item = document.getElementById("hi");
console.log(item);
item.data = {getType: function(){return this.TYPE},TYPE:"winner"};
var out = item.data.getType();
console.log("out", out);
var two = document.getElementById("hi")
console.log("should say 'winner': ", two.data.getType());

Can JQuery and Javascript be mixed together?

I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}

jQuery in console not working properly

I'm using the jQueryify bookmarklet on a page so that I can call jQuery functions from the console. But everytime I invoke a jQuery function on a selected object, I get the error:
"TypeError: jQuery("li")[0].children[0].html is not a function
[Break On This Error] jQuery('li')[0].children[0].html();
I have tried this in FireBug as well as Google Chrome's Webkit console.
You are no longer working with jQuery objects when using square braces.
jQuery("li")[0]
This returns you the 1st li as a DOMElement, not a jQuery object.
jQuery("li")[0].children[0]
This returns the 1st li's 1st child as a DOMElement, not a jQuery object.
.html()
This function only works for jQuery objects. For DOMElements, you can use the .innerHTML property.
I suggest instead of dealing with DOMElements, you should continue working with jQuery objects. Try using this instead:
jQuery('li').eq(0).children().eq(0).html()
It looks like you are trying to call a jQuery function, html, on a DOM object children[0]. Try wrapping that in a jQuery object and then calling html
var temp = jQuery("li")[0].children[0];
var html = jQuery(temp).html();
Check the result of jQuery("li")[0].children[0] , it's a regular DOM object NOT a jQuery object. Without seeing your HTML i can't recommend a better selector but a cheap and dirty fix would be
jQuery(jQuery('li')[0].children[0]).html();
This will convert the DOM object result into a jQuery object which has the .html() function.
Accessing the array elements on the jquery object (using []) returns a DOMElement, which obviously doesn't have jquery's methods. You probably want to use eq() instead.
Try following
jQuery(jQuery("li")[0].children[0]).html();
or better one
jQuery("li:eq(0)").children(':eq(0)').html();
or another one
jQuery("li:eq(0)").children().eq(0).html();
even this one will work
jQuery("li").eq(0).children().eq(0).html();

jQuery object html() doesn't work ... but innerHtml does

I have an object that should be a valid jQuery object. When I look at the variable in FireBug it contains all the jQuery functions I'd expect (clone, remove, removeat, etc.). However, I don't see html() as a valid function and when I do this:
stringValue = myjQueryObject.html();
It does fail, saying html() is not a function. However if I do something like this:
stringValue = myjQueryObject[0].innerHTML;
It will correctly pass back the object, minus the parent div and text (which I would expect, seeing as how it is just getting the innerHtml). What do am I missing here?
As noted below, it was an external library that was generating myjQueryObject that had previously returning a valid jQuery object and was updated ... incorrectly. For posterity's sake, I've updated my unit tests to verify that the external library returns a correct jQuery object, make sure this doesn't return null or undefined:
myjQueryObject.jquery
Thanks all! Had a bit of a freakout when my code suddenly broke this morning.
Either something is modifying the jQuery object prototype, or you have a different library loaded.
Take your object, and test for the jQuery version like this:
alert( myjQueryObject.jquery ); // should give the jQuery version number
EDIT:
Additionally, you state that there's a removeAt method. jQuery doesn't have one of those, unless you mean removeAttr().
Are you sure it's a jquery object? Wrap it in $() again and .html() should exist.
it's [0].innerHTML or .get(0).innerHTML, in that innerHTML is a property not a method.
You should make sure that jquery exists by doing alert( jQuery == $) and you can check for the .jquery property.
That's odd; try $(myjQueryObject).html();. If that works, the object isn't really a jQuery node.
If you still can't figure out why the object lost the html() method, post the code which creates it. Then, we might be able to help.
How are you setting myjQueryObject?
<div id='myElement'></div>
//Good Javascript, Incorrect jQuery
myjQueryObject = document.getElementById('myElement');
myjQueryObject.innerHTML = '<b>My HTML Here</b>';
//Correct jQuery
myjQueryObject = $('#myElement');
myjQueryObject.html('<b>My HTML Here</b>');
//Compact Version of Correct jQuery
$('#myElement').html('<b>My HTML Here</b>');

Categories

Resources