Is my code running jQuery? - javascript

The codebase I've inherited is full of $() methods and $.() methods.
eg.
$("#buttona").show();
$("#buttonb").show();
or
bComment = $.trim($("#aComment" + i).val().replace(/"/g, "'").replace(/\,/g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"));
Which leads me to believe that this is jQuery.
For example that trim method, appears to be a jquery method (takes a string as a parameter) rather than a core javascript method.
However, I can't see any reference to the jQuery source in the code base. I did a search for 'jquery' over the entire codebase, and couldn't find any src = jquery...js references- as said is necessary here..
How is it that this code could be otherwise running jQuery?

I'm answering this one, since Arun P Johny isn't answering.
Yes you are right. That's jquery.
You can check for its version by doing $.fn.jquery or jQuery.fn.jquery. This will return version.
The reason you didn't see a src = jquery..js might be because the script references may have been dynamically assigned. You can see which scripts were actually referenced by looking at the how the script was resolved in your browser (by pressing F12).
But Arun.P.Johny answered it first ;)

Related

jQuery: window.opener makes a difference

I'm working on localhost (so would expect to not have any domain-related probs as here).
On a page I'm using a bit of JS to modify the content of a span in the opening-window. It does not work.
When checking my code to find the control, it works (using FF dev-tools calling my Increment-function or checking the console.log-output): $('#uploads_Count')returns an object of type HTMLSpanElement. However, trying to access the same control from an opened window's console with window.opener.$('#uploads_Count'), this returns an HTML-Document, seemingly the entire page. Why is this not working, what am I missing here?
Here is function that is supposed to increment the counter contained in the span whose id is given as argument:
function Increment(ctrl)
{
var gef = $("#" + ctrl);
if (!gef) // did not find control, maybe on opener?
{
gef = window.opener.$("#" + ctrl);
}
console.log(gef);
cnt = parseInt(gef.text() , 10);
cnt++;
gef.text(cnt);
}
The HTML is trivial:
<span id="uploads_Count">0</span>
If $(selector) returns an element (such as HTMLSpanElement), rather than a collection of elements (would look like [<span id="uploads_Count"></span>] in most dev tools), then you're not calling jQuery.
Dev tools in A-grade browsers tend to introduce $ as a selector function. It is available in the developer console only.
If window.jQuery exists, then it's likely that jQuery.noConflict() was called, in which case you should use window.opener.jQuery.
Found it!
The way I checked if the control was found, was wrong. Instead of if (!gef)I should have used if (!gef.length). Found the explanation here.

jQuery: Unrecognized Expression (getting around this error)

jQuery("input[name=a.b.c]")
Executing this line using jQuery 1.10.2 or 1.9.1 results in the message:
"Syntax error, unrecognized expression: input:hidden[name=a.b.c]".
I understand the core problem which is that the dots are not escaped or quoted out. This would work:
jQuery("input[name='a.b.c']")
The constraint is that I do not have the ability to change the line of code with the bad selector. That line is produced by the website (which I don't own) and they don't give me the ability to change that.
However, they do allow me to add arbitrary JS files to the header of the page (which means I can use a different jQuery version or even edit the jQuery file). My question is whether anyone knows another way around this so that jQuery can cope without the quotes since I cannot change the bad code.
For those saying that I can just change the name, this doesn't help because the JS still throws an error because changing the name of the element doesn't fix the bad selector.
Thanks
The proper way of executing this selector is:
jQuery('input[name="a.b.c"]')
Obviously you need to edit the algorithm that creates this line, there's no way jquery will accept an invalid selector.
Take a look here.
How do I extend jQuery's selector engine to warn me when a selector is not found?
In your case I would do something like this.
var oldInit = $.fn.init;
$.fn.init = function(selector, context, rootjQuery) {
selector = fixItWithQuotes(selector, context, rootjQuery);
return new oldInit(selector, context, rootjQuery);
};
untested by me, but it should give you an idea.
Also, this might give you more ideas?
http://blog.tallan.com/2012/01/17/customizing-the-default-jquery-selector-behavior/
Hope that makes sense.
Why don't you change the name attribute yourself?
var el = $("input");
el.attr("name", el.attr("name").replace(/[\d\.]+/g, ""));
console.log(el.attr("name"));
Then change it back if you need to. jsFiddle here

... (three dots) in jQuery?

I was looking at the documentation page for jScroll plugin for jQuery (http://demos.flesler.com/jquery/scrollTo) and I noticed this :
$(...).scrollTo( $('ul').get(2).childNodes[20], 800 );
So, what does the three dots in jQuery mean ? I have never seen this selector before
EDIT :
DOM Element
This is from the source HTML. Viewing the source for the following links :
Relative
selectorjQuery
objectDOM
ElementAbsolute
numberAbsolute
all give the same implementation.
EDIT : I didnt look at the attribute clearly, its for the title attribute. I assumed its the href attribute. Feel silly asking this question now :) Thanks for the answers
I am fairly certain that he was using that as an example.
$( ... ) would be akin to $( your-selector-here ).
In other words, I have never seen any implementation of that.
Typically ... is used in various docs to shorten the example, and it means that you put something in place of the dots, or that what you would put there was omitted (to shorten the example)
It's not actually valid JS syntax.
It has no meaning. They meant just write your own selector.
Check out the souce code
$('div.pane').scrollTo( 0 );
They are not syntactically correct. They are just way the author uses to say scroll to some element, the name of which I don't bother to write here so I just write dots. Check the source code of the page if in doubt.
Three dots in javascript is Spread Syntax see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals)

Chrome extension read innerHTML of the current page?

Hi this may be a silly question, but I can't find the answer anywhere.
I'm writing a chrome extension, all I need is to read in the html of the current page so I can extract some data from it.
here's what I have so far:
<script>
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
alert(document.innerHTML)
});
}
</script>
Can anybody tell me what I'm doing wrong?
thanks,
function windowLoaded() {
alert('<html>' + document.documentElement.innerHTML + '</html>');
}
addEventListener("load", windowLoaded, false);
Notice how windowLoaded is created before it is used, not after, which won't work.
Also notice how I am getting the innerHTML of document.documentElement, which is the html tag, then adding the html source tags around it.
I'm writing a chrome extension, all I need is to read in the html of
the current page so I can extract some data from it.
I think an important answer here is not the correct code to use to alert the innerHTML but how to get the data you need from what's already been rendered.
As pimvdb pointed out, your code isn't working because of a typo and needing document.documentElement.innerHTML, something you can diagnose in the Chrome console (Ctrl+Shift+I). But that's secondary to why you'd want the inner HTML in the first place. Whether you're looking for a certain node, specific text, how many <div> elements exist, the value of an ID, etc., I'd heavily recommend the use of a library like jQuery (vanilla JS works, but it can be verbose and unwieldy). Instead of reading in all the HTML and parsing it with string functions or regex, you probably want to take advantage of all the DOM parsing functionality already available to you.
In other words, something like this:
$("#some_id").val(); // jQuery
document.getElementById("some_id").value; // vanilla JS
is probably way safer, easier and more readable than something eminently breakable like this (probably a bit off here, but just to make a point):
innerHTML.match(/<[^>]+id="some_id"[^>]+value="(.*?)"[^>]*?>/i)[1];
Use document.documentElement.outerHTML. (Note that this is not supported in Firefox; irrelevant in your case.) However, this is still not perfect as it doesn't return nodes outside the root element (!doctype and possibly some comments or processing instructions). The document.innerHTML property is, AFAIK, specified in HTML5 specification, but currently not supported in any browser.
Just FYI, navigating to view-source:www.example.com also displays the entire markup (Chrome & Firefox). But I don't know whether you can work with it somehow.
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
alert(document.documentElement.innerHTML);
}
You had a } with no purpose, and the }); should just be }. These are syntax errors.
Also, it's document.documentElement.innerHTML, since it's not a property of document.

Is it possible to get jquery objects from an html string thats not in the DOM?

For example in javascript code running on the page we have something like:
var data = '<html>\n <body>\n I want this text ...\n </body>\n</html>';
I'd like to use and at least know if its possible to get the text in the body of that html string without throwing the whole html string into the DOM and selecting from there.
First, it's a string:
var arbitrary = '<html><body>\nSomething<p>This</p>...</body></html>';
Now jQuery turns it into an unattached DOM fragment, applying its internal .clean() method to strip away things like the extra <html>, <body>, etc.
var $frag = $( arbitrary );
You can manipulate this with jQuery functions, even if it's still a fragment:
alert( $frag.filter('p').get() ); // says "<p>This</p>"
Or of course just get the text content as in your question:
alert( $frag.text() ); // includes "This" in my contrived example
// along with line breaks and other text, etc
You can also later attach the fragment to the DOM:
$('div#something_real').append( $frag );
Where possible, it's often a good strategy to do complicated manipulation on fragments while they're unattached, and then slip them into the "real" page when you're done.
The correct answer to this question, in this exact phrasing, is NO.
If you write something like var a = $("<div>test</div>"), jQuery will add that div to the DOM, and then construct a jQuery object around it.
If you want to do without bothering the DOM, you will have to parse it yourself. Regular expressions are your friend.
It would be easiest, I think, to put that into the DOM and get it from there, then remove it from the DOM again.
Jquery itself is full of tricks like this. It's adding all sorts off stuff into the DOM all the time, including when you build something using $('<p>some html</p>'). So if you went down that road you'd still effectively be placing stuff into the DOM then removing it again, temporarily, except that it'd be Jquery doing it.
John Resig (jQuery author) created a pure JS HTML parser that you might find useful. An example from that page:
var dom = HTMLtoDOM("<p>Data: <input disabled>");
dom.getElementsByTagName("body").length == 1
dom.getElementsByTagName("p").length == 1
Buuuut... This question contains a constraint that I think you need to be more critical of. Rather than working around a hard-coded HTML string in a JS variable, can you not reconsider why it's that way in the first place? WHAT is that hard-coded string used for?
If it's just sitting there in the script, re-write it as a proper object.
If it's the response from an AJAX call, there is a perfectly good jQuery AJAX API already there. (Added: although jQuery just returns it as a string without any ability to parse it, so I guess you're back to square one there.)
Before throwing it in the DOM that is just a plain string.
You can sure use REGEX.

Categories