Specifying the HTML page that a jQuery selector refers to? - javascript

I'm trying to write jQuery code to count the number of <img> elements contained on a site. The site is comprised of 4 separate HTML pages, all in the same folder on the server. Only one of these pages, "pics.html", loads the .js file that needs to perform this function (pics.html is the only page that needs to know how many images are on the site).
It's easy to get the <img> elements from pics.html, since pics.html is the page that loads the script:
var numImgs = $('img').length;
...but I'm confused as to how I would perform this same function in reference to a different page. Is it possible to specify the HTML page that the selector refers to?
I tried this, as a wild guess:
var numImgs = $('test.html:img').length;
Unsurprisingly, it didn't work. I googled for the answer, but couldn't find a solution - or if I did find one, I suppose I didn't understand it well enough to realize that it was the answer.
Thanks for any help you can offer!

To select an object from an external file, you'll need to use $.load().
Reference: http://api.jquery.com/load/

Try this
$(document).ready(function(){
$('#myDiv').load('/remotePage.html #TargetDiv', function () {
var elements = $('.class', this).length;
alert(elements);
});
});

Related

jQuery refer to files in folders

$(function () {
$(".links2lvl a").click(function () {
var page = this.hash.substr(1); /*in case of first link - works*/
/* var page = this.hash.substr(7); in case of second link - nope.jpg*/
$.get(page + ".php", function (gotHTML) {
$("#content").html(gotHTML);
});
});
});
<section class="tabs">
<ul class="links1lvl">
<li><a>About</a>
<ul class="links2lvl">
<li>Us</li>
<li>Personal</li>
So here I have two two sets of code. First is jQuery function, which extracts given PHP file and it's contents are shown in div with id="content".
The other is my 2 level list. In the second level you can see pages I'm trying refer to. The first link works just fine, jQuery successfully extracts the content and shows it given plave, but the second link in the folder about/ thats another story, the function doesn't seem to find it. The question is, how do I refer to .whatever from another file?
Most of the problems I see in code are based on attempts to solve challenges by adding more challenges to the code. :)
I would give a suggestion and I hope you don't mind: I would solve it by adding a "data-*" to each a tag to hold the reference you need to find using this.hash (or, maybe, use .each or .map) to loop through the elements and extract the proper URL to be used).
What happen is, this.hash will return "#who", but it is also a valid ID selector in jQuery (see more here). Hence this.hash will find "#who", but won't find "about/#personal" (because the hash element is not the first character of the string).
You could use string.split('#') to capture the string straight after the "#", then save it in - for instance -, the data-hash parameter at each a tag while constructing the HTML. Then it should be fairly easy to obtain the content needed for your application (once again, it is always about how to minimize challenges, instead of add them). ;)
Sadly I am no able to build a code sample now, but if you have difficulties following this idea, contact me and I will write a quick sample code for you.

using javascript to output html

I have a javascript link that references another .js file. I've been trying to output an image (for testing purposes), but I'm not sure what is the correct way to go about this.
alert("beginning");
//var link = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
//$('body').append(link);
//document.write("hi");
//document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("before function");
(function(){
alert("middle");
var links = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
$('body').append(links);
alert("after middle");
//alert($("img").attr("id"));
document.write("hi");
document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("end");
}());
I was able to alert beginning, all the way to middle. It seems like var links doesn't work. I'm trying to use HTML inside this .js file. Essentially, I want to be able to do some modal window, but I'm trying to output images for testing purposes right now.
Also, is this the correct way for jquery?
Thanks in advance!
Your code is a strange mix. Jquery code almost always needs to run after the page has loaded whereas document.write can never be used after the page has loaded.
You are incorrectly wrapping your jQuery in an immediate executing function. The proper wrap for jQuery is within :
$(document).ready(function(){
/* html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
or the shorthand version that does same thing:
$(function(){
/*html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
If you change all of your document.write to $('body').append(/* your content*/) and place all your code inside the above wrappers you will have much better success.
There is a wealth of information within the jQuery documentation and API. A good start point with more detail about the wrapping I've shown can be found here: http://docs.jquery.com/How_jQuery_Works
Your biggest problem is addressed in the other answer. You are improperly wrapping JQUery so essentially JQuery is not ready to be executed when it reaches your append statement.
It is unnecessary to wrap your html in a JQuery object (in this case):
var links = "<a href='http://juixe.com'>Hello, <b>World</b>!</a>";
$('body').append(links);
or simply:
$('body').append("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
In terms of best practice, using append, appendTo or prepend are good options depending on the context. You could also use:
$("body").html("/*Your HTML here*/")
At the end of the day you have many options but avoid document.write at all cost. The non-JQuery approach would be to use .innerHTML with a DOM element. This is also a good approach in the absence of JQuery.

how can I detect page when I compile all javascript to one file

I compile all my javascript for different pages into one file, so I have to identify page for my all.js. I can put a hidden element in my pages and let javascript detect this element, but I don't like this solution, are there any other ways to do this?
You could go by the url using location.href (or another field from the location object).
However, a better approach is using a data- attribute on the body tag, e.g. <body data-page="whatever"> and then using $('body').data('page') to retrieve the value.
If you script is based on pages, then compiling them into one script is a bad idea, load the file separately, it will be lighter and definately increase some performace.
I am not sure, why do you need this, but in general it is not good practice to change dynamicaly change content of javascript file, since you are disabling javascript cacheing, what can be performance issue later.
Any way, you can solve it from other side, what about using all.js just to detect the page, where are you and then you can use this information, to load right javascript file dynamicaly, like in the following example
document.write('<script src="'+location.pathname+'.js"></script>');
Which will load same file as you are on, just with .js extension. So for example on index.html page it will load index.html.js file
I almost always use MVC frameworks and tend to put my action and controller as classes on the body element
<body class="main_controller index">
Which lets you do things like this:
$(document).ready(function(){
//Only for lessons#search
if (!$(body).hasClass('lessons search')) {
return;
}
function close_style_filter_box() {
$('#style_filter_box').slideUp();
}
});
$(document).ready(function(){
//Only for main_controller#index
if (!$(body).hasClass('main_controller index')) {
return;
}
function do_something_else_on_this_age() {
....
}
});
Another way is using javascript variable:
var PAGE = 'page1';

jQuery - dynamically remove head elements on click

Does anyone know if you can remove head elements on a button click and how to do it with jQuery?
I am trying to get rid of certain script tags from the html head when a button is clicked.
For instance. I have 1 screen view with a slideshow controlled by an external javascript file. When I click on a button "Click to get rid of this elements JS" I want to remove the external javascript path from the HTML Head.
Any ideas. Have been at this thing for a week or so.
You can add an id to a script element then remove that ID:
<script type="text/javascript" src="init.js" id="initJs" ></script>
<span id="removeScript"></span>
$('#removeScript').click(function() {
$('#initJs').remove();
});
You can do this sort of thing using javascript, sure, but before you do it, you might want to ask yourself again why. Here's a link describing how to do it in pure javascript with a jquery example provided by the other answerer:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
But try to keep in mind that most modern browsers will keep these external resources in memory for at least as long as the page is open. Therefore, you won't really be doing much.
I don't think its a good Idea to remove Entire HEAD Element. 'Cause your Page may contain some more Elements (i.e., title, style..) which are appended to Head Element. If you want to remove a particular script Element do something like
$(function() {
$('input[type=button]').click(function() {
$('script[src=path/file.js]').remove();
});
});
Edit :
var flag = false;
function breakTheCode() {
if(!flag) {
//run your code
}else return;
}
$(function() {
$('input[type=button]').click(function() {
flag = true; //flag is set, so we no more using/ running your code
breakTheCode(); //call you function/method
});
});
For my part the best solution is to use ID on the scripts.
I read many page over the web, try many solutions, and the only one who works fine every time is to remove a script like a div with an id !
For remove js file : $("script[src='your.js']").remove();

How can I use javascript to convert relative href attributes into absolute paths?

I have a template that gets screenscraped from an outside vendor and need to include absolute paths in the navigation so the externally hosted content will properly link back to our site.
Right now the page/template is driven by a global menu app written by our back end development staff... so anyone who updates our site goes in and changes the menus and their paths...
Right now all of the links are linking to relative paths back to the root.
For example
Home
News
Media
Other
I need a simple way (preferably with jquery) to prepend "http://www.domain.com" to each of those links.
Please note that jQuery object $("a").attr("href") is not equal to $("a").get(0).href ?
$("a").each(function() {
alert(this.href);
$(this).attr("href") = this.href;
});
In you case, this may not help you , because you want static markup, javascript generate dynamic content. But it seems that you want static markup in that case it has to be emit by server.
$('a').attr('href', 'http://www.domain.com'+$(this).attr('href'));
I don't recommend using javascript to solve this issue. This should be solved in the page template. However, if you still want a jquery solution then here you go. Assuming those links have a specific class that distinguish them from internal links:
$('a.external').each(function() {
$(this).attr('href', domain_name + $(this).attr('href'));
})
you don't need jquery for such a simple function....
var elements = document.getElementsByTagName("a");
var eachLink;
for (eachLink in elements) {
var relativeLink = eachLink.href;
var absoluetLink = ["http://",domainName,"relativeLink"];
eachLink.href = absoluteLink.join("");
}
something like this should work, and it runs much faster and you won't need to load the entire jquery library just to run 6 lines of code :P
It's very simple:
$('a').each(function(){$(this).attr('href',this.href);});
When you read the href property of a HTMLAnchorElement, you get the absolute path, so you can overwrite it with attr() method of JQuery.
I noticed that all the solutions here only work with href attributes that begin with a "/" character. If you want something more robust, you may want to try the js-uri library. It looks cool but I haven't tried it myself so I don't know how buggy it is.

Categories