revise href attribute - javascript

So I have a link like this:
<a href="http://thissite.org/thisfolder/21/thispage.php">
What I want to do is revise it but keep part of it eg:
<a href="http://thissite.org/thatfolder/21/thatpage.php">
Can this be done with Jquery or js?
I know I can replace href property with jquery but I need to leave part of the url ("21") and just change the text before and after it.
I was thinking maybe grab the href property, stick it in a variable and take it apart and put it back together somehow.
Any help with this would be largely appreciated.

You can call replace in a property setter function:
$('a').attr('href', function(index, old) {
return old.replace(/thisfolder/i, 'thatfolder');
});

A rough way of doing this would be:
// "elem" is the element, for example elem=document.getElementById('link_to_change')
var url = elem.getAttribute("href").split("/");
url.pop();
url.push("thatpage.php");
elem.setAttribute("href",url.join("/"));

Related

jquery set base href

I'm trying to set the base href with JQuery by reading a PHP file.
Why does $("base").load("ip.php"); work but $("base[property='href']").load("ip.php"); doesn't?
Of course what I need is to set the href parameter only, not the content of base.
I found I could get it working by using $("head").load("ip.php"); but would like to know why above isn't working.
Try something like this to set href value
$('base').attr('href','http://www.google.com');
Its depend how your file ip.php is
For example
ip.php
<?php
echo 'http://www.google.com';
?>
Then
$.get('ip.php',function(response){
$("base").attr("href", response);
});
I don't know exactly, but in my opinion, u got the meaning of the selector wrong. I think [property='href'] is not a valid selector. href is the property you should search for, and not the value.
You can select DOM-elements with jquery using $("base"). Additionally you can use a key-value combination to search for certain attribute-values of your element.
$("a[href$='.org']")
With this selector you would select elements with a href attribute which ends with '.org'.
So the point is: you still select the DOM-element and NOT a part of that element. But your search is better specified.
just need :
window.location = "http://yoursite.php";
dont use load, use $.ajax!
$.ajax({
url: "ip.php"
}).done(function (data) {
$("base").attr("href", data);
});

javascript not working dynamically created javascript alink

This isnt working, not sure what is wrong. I dont want to use href onclick at all, i usually use an id on ahref links then execure javascript that way but i need to pass parameters from the link to the function, not sure if there are other alternatives?
code using the parameters isnt shown, its basiacly a forum link but its loading the topic into a div
function changetotopicdetails(topicid, topicname) {
$('#loadingAjaxs').show();
$('#flubestext').hide();
#following.Title
I would usually do something like
$('#changeuserstwohour').click(function () {
$('#userswrap').load('#Url.Action("TrendingUsersMenutwohr", "Trending")');
});
but by doing so i cant send parameters to the function during a loop (list of topics)
any suggestions?
Answers pointed out that i need the variables passed to a new {}
$('#changeuserstwohour').click(function () {
$('#userswrap').load('#Url.Action("TrendingUsersMenutwohr", "Trending", new {#theid = id, #thename = name})');
});
You could do your usual click function, eventListener or bind and use data values to indicate you username and trending values.
so your tag would look like
<a href="#" data-id='#following.Id' data-short-name='#following.ShortName'>#following.Title</a>
and then your usual click function which would look like
$('#changeuserstwohour').click(function () {
$('#userswrap').load('#Url.Action($(this).data(id), $(this).data(short-name)');
});
you may need to use .each() if you have multiples or call it after each ajax load to make sure its listening to the new objects. I haven't tested this as I dont really have the functions but this should work! Please let me know how it goes and if you have another question :)
A combination of both techniques provided so far is what you're probably really after.
Your markup for your individual action links would look like:
<a href="#" class="selectorForYourActions" data-id='#following.Id' data-short-name='#following.ShortName'>#following.Title</a>
and then your on-click callback which would look like
$('#idOfContainerYourLoopCreatesItemsWithin').on("click", "a.selectorForYourActions", function () {
$('.userswrap').load('#Url.Action($(this).data(id), $(this).data(short-name)');
});
This will catch any dynamically created items that match that class if they are created within the element selected by the ID selector, but only handle clicks on anchor tags with the marker class, so you can both have many of those anchors with unique (or no) Ids and anchors with normal (or different) functionality.

Javascript in html syntax in link

I am having a problem adding a js variable inside a html link where I believe I have the syntax wrong as it's not adding the content of the variable to the link string.
Here is what I'm trying:
href="http://www.facebook.com/sharer.php?u='+url+'">
Where I'm I going wrong here?
That is not possible to do :).
You have to do it javascript all the way, like:
href="javascript: document.location='http://www.facebook.com/sharer.php?u=' + url;"
You are trying to treat HTML as if it were JavaScript. You can't just jump in and out of the two languages.
If you want to modify an existing link, you need to use DOM Manipulation. This is covered as part of the introduction to JavaScript hosted by the W3C.
You can't do that. You will need to use javascript like this:
... within <head> tag ...
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').href = "http://www.facebook.com/sharer.php?u="+url;
}
</script>
... within <body> tag ...
<a id="myLink" />
You need to be outside of the string in order to concatinate your URL.
In this case your string is created using a double quotation mark however you're trying to break out of the string by using a single quotation mark.
I'm assuming here that html is a Javascript variable, which it might not be:
var href = "http://www.facebook.com/sharer.php?u=" + url + ">";
I do not think you can just add a javascript variable inside an href like that. Try this:
Foo
document.ready(function(){
var url = "yahoo.com" ;
$("#linkid").setAttribute("href",url) ;
}) ;
When the browser loads all the elements, document.ready executes the method to set the href attribute of your anchor tag.
So you have an anchor tag like so:
<a id="linkid"/>
$("#linkid") gets the anchor tag element, while setAttribute("href", url) will set the link to your href attribute.
Hope it makes sense.

Firefox add <a xmlns="http://www.w3.org/1999/xhtml">

EDIT: This isn't happening because of the ajax call. I changed it to use a value from a TinyMCE component for fun and I get the same thing.
content = tinyMCE.get('cComponent').getContent(); //content at this point is <p>test</p>
valueToDisplay = content;
If I do:
jQuery(selector).html(valueToDisplay);
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p>
Has anyone ever seen this before using Firefox 3.6.10 and jQuery 1.4.2, I am trying to change a link text using the result from a jQuery ajax call.
I get the result expected from the ajax call:
function getValueToDisplay(fieldType){
var returnValue;
jQuery.ajax({
type: "GET",
url: "index.cfm",
async:false,
data: "fieldtype="+fieldType,
success:function(response){
returnValue = response;
}
});
return returnValue;
}
If I check the value at this point I get the expected value
console.log(returnValue) //output this --> <p>Passport Photo</p>
However when I use jQuery(selector).html to insert it inside of an existing anchor
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">Passport Photo</a></p>
I have been trying to figure out where that xmlns anchor is added but can't narrow it down to anything specific.
EDIT: I have tried forcing dataType:"html" in the ajax call...no change.
Your selector represents something that is, or is in an a tag.
A much more minimal version of your problem would be:
html:
<a id="test"></a>
js:
$('#test').html('<p>test</p>');
result:
<a id="test"><p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p></a>
Change things around so you aren't putting p tags in an a tag, or do the following:
$('#test').empty().append('<p>test</p>');
I would like to extend the answer, as of why is happening, and provide a workaround.
Doing a GreaseMonkey script i was trying to change the content of an element, perhaps not changing per se but adding more elements as the tag had only an IMG inside.
Original:
<a onclick=something><img src=url></a>
What i tried to do was to insert a DIV element that would wrap the already IMG and another new SPAN second child, so the objetive was to end up with this:
<a onclick=something><div><img src=url><span>text</span></div></a>
Using the innerHTML property it would be like this:
ANode.innerHTML = '<div>' + ANode.innerHTML + '<span>text</span></div>';
but instead i got:
<a onclick=something><div><a xmlns="http://www.w3.org/1999/xhtml"><img src=url><span>text</span></a></div></a>
Looking at the answers here did help a bit although there's no real explanation. After a while i noticed something that does not happens with the example in the question, which now i believe is the key to this issue. I was the same as jfrobishow thinking where was it happening, i thought there was something wrong concatenating the ANode.innerHTML.
Answering, at the original question, the part of narrowing it down to where does this happens, notice that the out-of-nowhere <A> was enclosing both the IMG and the new SPAN nodes, so this made me curious, the unwanted <A> was being added just before the DIV element was "built". So from this, the original example, and my following workaround you can notice that this happens when you insert a new BLOCK node inside an Anchor, as both DIV and P (original example) elements are BLOCK elements.
(If you don't know what i mean by BLOCK is from the display property of an element http://www.w3schools.com/cssref/pr_class_display.asp)
The obvious workaround is to replace the type of node you're inserting, to a non-block element, in my case the problem was the DIV i wanted, but of course it depends on the objective of your script, most of the things are there by design, i put a DIV because i needed it, so i fixed it turning that DIV into another SPAN ( which is an inline element) but i still needed to behave like a block element so put the style, this is what worked for me:
ANode.innerHTML = '<span style="display:block;">' + ANode.innerHTML + '<span>text</span></span>';
So, plainly, this problem is not from scripting (Javascript for me) but from style (CSS) stuff.
BTW, this happened at Firefox 3.6.18, notice this does not happens at Firefox 5.0.
The problem is placing block elements inside an anchor tag.
This is not valid HTML, even though most browsers will parse it fine.
You just need to use a <span></span> element inside the anchor, instead of a <div> or <p>.
This is happening because in your <html> you declared a XML Namespace (xmlns). If the xmlns anchor is not breaking anything, just leave it there.
Also, don't use async:false, make a callback function to be called on success.
EDIT: Actually that just fixed the issue with that particular value... it started happening on other values where it used to be fine.
Somehow this fixed the issue.
Changed
jQuery(selector).html(valueToDisplay)
to
jQuery(selector).html(
function(index, oldHtml)
{
return valueToDisplay;
}
);
According to the doc, if I read it right it should be doing the same thing as I am not using oldHtml in the function. (http://api.jquery.com/html/).
From the doc: "jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content."
Try changing dataType in your ajax call to "text"
Using .append() instead of .html() fixed the issue for me. Never seen this before today. Why is it adding the extra xmlns? I tried changing my dataType to "text" as well, but it didn't work. It was really messing up my CSS styles as well, but using .append() completely resolved the issue. Thanks!
UPDATE: I needed to completely replace the content of my div with the result of an .ajax() query. .append() by itself wasn't sufficient, as it would just add to the content, so I found another workaround:
First clear the div:
$("#myDiv").html("");
Then, append the content using .append():
$("#myDiv").append("My content");
It's not perfect, but it works.

Using jQuery, how do I change the elements html value? (div)

Using a ajax request I want to change content of my div.
<div id="d1">202</div>
So I want to change the content to a different number.
$('d1').InnerText???
Also, say I wanted to increment the number, how could I do that? Do I have to convert to int?
$("#di").html('My New Text');
Check out the jQuery documentation.
If you wanted to increment the number, you would do
var theint = parseInt($("#di").html(),10)
theint++;
$("#di").html(theint);
P.S. Not sure if it was a typo or not, but you need to include the # in your selector to let jQuery know you are looking for an element with an ID of di. Maybe if you come from prototype you do not expect this, just letting you know.
This would changed the inner text of your HTML element.
$('#d1').text(parseInt(requestResponse)++);
Unless you're embedding html like <b>blah</b> I'd suggest using $("#di").text() as it'll automatically escape things like <, > and &, whereas .html() will not.
Use the text function:
$("#d1").text($("#d1").text() + 1);
$('#d1').html("Html here");
jQuery('#d1').html("Hello World");
if your value is a pure text (like 'test') you could use the text() method as well. like this:
$('#d1').text('test'); Or $('#d1').html('test');
anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:
$(document).ready(
function() {
$('#d1').text('test');
}
);
this way the script executes after the HTML of the div is parsed by the browser.
$("#div1").innerHTML="your text goes here..";

Categories

Resources