jQuery - Trouble adding a class to a hyperlink using 'each' - javascript

I have some Javascript that finds all of the hyperlinks in a page that contain 'google' for example and changes the beginning of the url to another url.
I am trying to add a class to this affected link, however I am getting a lot of 'undefined' errors in the JS console. I have tried alert($(this).innerHTML)) which showed the contents of the hyperlink - clases and whatnot. But for some reason I cannot append a class. I have also tried using this.className += " socks". That also causes an undefined error. I think I am missing something simple!
Also is there a way of using a regex in the search, I am newish to Javascript.
Here is my code:
$("a[href*='google']").each(function(){
this.href = this.href.replace('http://www.google.co.uk','http://www.ask.com');
this.href = this.href.replace('http://www.google.com','http://www.ask.com');
$(this).addClass("socks");
});
Thanks very much for any help!

There is no error with this code that i can see:
http://jsfiddle.net/p7Sgj/
See this.

try
$("a[href*='google']").each(function(){
var href = $(this).attr('href');
href.replace('http://www.google.co.uk','http://www.ask.com');
href.replace('http://www.google.com','http://www.ask.com');
$(this).attr('href', href);
$(this).addClass("socks");
});
instead of using this.href. I guess your code doesn't reach the addClass part...
Also, use firebug (in case of firefox) or chrome developer tools (in case of chrome) for debugging. You can simply set a breakpoint, add watches, etc...
(In that case, make sure you use a so-called non-minified version of jQuery for easier debugging)

If your HTML code is
Hello
World
And your CSS is
.socks {
color:#f00;
}
Then your code should be working fine.
http://jsfiddle.net/k93TZ/2/
Working here.
It might be your html or css code.

Related

Remove numbers on a html page using jQuery

I want to make some jQuery actions on a html page :
The page is : http://download.eclipse.org/jetty/stable-9/xref/org/eclipse/jetty/embedded/HelloHandler.html
my aim is to remove the numbers (represented by the class jxr_linenumber)
What I've tried is :
$(".jxr_linenumber").text("")
However google chrome said : Uncaught TypeError: $(...).text is not a function(…)!!
Even more ... when I tried this command $('a'), it returns with one element only ... however the page contains several "a" tags
Here is two screenshots to explain the issue and my goal
The screenshot of the actual page :
My goal = remove the numbers using jquery ... the numbers are in the red box ....
So the result should be as follow :
Any help ? thanks
The .remove() should do the trick, but my guess is that its causing some issues since jquery isnt available on the page, and injecting it after, might be why its only removing one at a time.
You could use plain javascript like this:
var elements = document.getElementsByClassName("jxr_linenumber");
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
Try the Jquery function .remove( ) instead. Something like
$(".jxr_linenumber").remove( );
You use...
$(".jxr_linenumber").html("")
but in the end, the best answer is to use $(".jxr_linenumber").remove() since you don't want empty 'a' tags on your page. That's just bad design.

Why is CKEditor removing links and attributes

I have a link with an inline attribute of style="color: #FF0000;". I recently upgraded to latest CKEditor, after years of neglect. Now when I call CKEDITOR.inline, it strips all the links.
I found http://docs.ckeditor.com/#!/api/CKEDITOR.dtd-property-S-editable, which doesn't have an a in there.
I did CKEDITOR.dtd.$editable.a = 1; and it still strips links. What am I missing here? I literally followed the flow from the API inline call to that, but it seems that I'm doing something wrong.
EDIT
I also find that is removing the class attribute from elements. Everything else seems okay.
Check out the guide about content filtering (ACF) in CKEditor. See also the working sample in CKEditor SDK which shows how ACF works in the default automatic mode and how to adjust it (which is what you need to do in your case).
try this:
CKEDITOR.config.allowedContent = true;
CKEDITOR.dtd.$removeEmpty['a'] = false;
CKEDITOR.config.extraAllowedContent = 'a[!href];' + '#';
CKEDITOR.config.protectedSource.push(/<a[^>]*><\/a>/g);
CKEDITOR.config.protectedSource.push(/<span*?[\s\S]*?\/span>/g);

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.

Onclick JavaScript not working properly in IE

Please excuse my ignorance I am not very familiar with JavaScript and have been tasked with repairing a bug by a developer no longer at the company.
The onclick works perfectly in FireFox, however in IE 7&8 (the only ones we test for), it appears to run through the onclick functions properly, then instead of the data being submitted to the form URL in goStep3(), it runs through every onclick on the page, with href="#" then finally submits with incorrect information as the variable has been overwritten 50 times.
view
EDIT:
When I run trackSponsor(62, 64265); goStep3(1896, 64265, 0); return false; in the Developer Tools in IE8 I get an error of returning false outside of a function....removing that it works just fine.
Is the line that I believe is causing the problems?
trackSponsor() is working properly and returns false
goStep3() is quite a large function however it works by retrieving values from 4 other functions within, assigning the values to a URL within theAction
It completes the function by EDIT:
var yr = $("#find-yr").attr('value');
var me = $("#find-me").attr('value');
var mo = $("#find-mo").attr('value');
var keywords = $("#find-keywords").attr('value');
var theAction = PATH_BASE+'find/step3/'+p_term+'/'+p_id+'/'+p_l_id+'/';
document.forms['FindForm'].action = theAction;
document.FindForm.submit();
return true;
I have tried returning false from this function, as well as changing the document.FindForm.submit() to the 'correct' syntax of document.forms['FindForm'].submit() and it still does not submit until running through all of the other onclick s on the page.
Thanks in advance!
Notes:
jQuery is being used as well.
Javascript is not throwing any errors.
This works fine in FireFox
I can see it going through all of the other functions in the other onclicks using Developer Tools and stepping through the page it does not submit the results of goStep3 until it has gone through all of the other onclick functions on the page.
"posting my earlier comment as an answer"
I see a lot of jQuery being used with attribute selectors, so plz check the code against those.
EDIT:
I noticed ur unfamiliar with JavaScript... so in-case u didnt know, a jQuery selector, will select all tags matching a certain "selector-filter" and perform a certain action on them... so if there is a selector that selects all A tags with a href attribute (or maybe another common attribute between them...) then that would be the cause of your problem.
EDIT: -after you posted your answer -
glad you found an answer...
though it is alittle werid,
cause according to your question it goes through "every element with href="#" ...
However According to msdn, Event bubbling simply passes these unhandled events to the parent element for handling. not through "similar" tags :)
oh well..nothing is logical when it comes to IE
I would start by removing "return false;" from the onClick event since it really isn't doing anything.
try changing
href="#"
with
href='javascript:void(0)' .
I can't say for sure where things are going wrong, but I discourage using a form's name attribute to reference it like you have done here:
document.forms['FindForm'].action = theAction;
document.FindForm.submit();
Why not try the following jQuery:
$("form:FindForm").action = theAction;
$("form:FindForm").trigger("submit");
You should also check that $("form:FindForm") is indeed referencing the desired form element.
The problem was called because of how IE uses the bubble! Thanks all for your help, I have included the code solution to be placed in goStep3().
var browserName = navigator.appName;
if (browserName == "Microsoft Internet Explorer") {
window.event.cancelBubble = true;
}

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