Split value of a html tag - javascript

I would like to split some content from an "a" html tag. I was starting over with jquery. My code is like this but it is not working:
$("a.uribb").each(function() {
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).append(+id+);
});
​
And the HTML tag is this:
<a href="http://dereferer.org/?http://example.com/" target="_blank" class="uribb">
http://example.com/
</a>
I wanted to split out the http://dereferer.org/? part and leave the other there. How could I do this?

Try to use .text() instead of .append() if you want to replace the content. Also, there is no need for the + before and after the id.
You could try this instead:
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).text(id);
Update
Reading through the question again, I'm not sure if you want to replace the content of the a-tag or the the value of the href. In case of the latter, try this:
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).attr("href", id);
Notice
Since jQuery 1.6, it is preferred to use .prop() instead of .attr().

How about that?
$("a.uribb").attr("href", function(i, val) {
return val.substring(val.indexOf("?") + 1);
});​
DEMO: http://jsfiddle.net/zQdL4/
It's interesting but for your markup the following code should also work :)
$("a.uribb").attr("href", function() {
return $.trim(this.innerHTML);
});​

Right, so what you want is this.
<a href="http://example.com/">...
Try this.
$("a.uribb").each(function() {
var indirect_url = $(this).prop("href");
var direct_url = indirect_url.replace("http://dereferer.org/?", "")
$(this).prop('href', direct_url);
});
You could of course do this in fewer lines, but this way it's clear what's going on. Specifically, replace() does not modify the string it operates on.

Related

How to check if href attribute contains a string?

I want to get all "a" tags from page, get its "href" attribute and check if in this href is text ".pdf". So I get all a tags into tags variable, then with each() function I check every "a" (as a tag). But code:
if ($(tag).indexOf('.pdf') > 0)
console.log($(tag));
is not working. Why? Why I can't use indexOf on href? I tried with search() function, but it's also not working.
So I thought - ok, there's something wrong with this href. Lets take it as a text.
But code:
var text = $(tag).text();
console.log(text);
is also not working. Can anybody tell me why?
Code snippet has errors intentionally - to show with what I have a problem.
Thank you in advance.
(function($){
var tags = $('a');
$(tags).each(function() {
var tag = $(this).attr('href')
if ($(tag).indexOf('.pdf') > 0)
console.log($(tag));
var text = $(tag).text();
console.log(text);
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
Link with ".pdf"
Link without ".pdf"
</html>
No need to for the additional $(tag) when calling indexOf. tag is a string at that point and you don't need to make it a jQuery object. simply call tag.indexOf('.pdf') > 0. For strings you can also use tag.includes('.pdf') or you go for tag.substr(tag.length - 4, 4) === '.pdf' to make it even more precise.

Replace a href with a js function call

I want to replace an url in a href with a call of a function that needs to include the url.
example:
I have the following string:
Google
some other text
Wikipedia
I want to get back a string like this:
Google
some other text
Wikipedia
I have tested some ways with RegEx, but I'm not good with RegEx. Does anyone have a solution for my problem?
EDIT:
Sorry, I forgot to write. I'm building an appcelator application. I can't use jQuery or "document". I think the only way is a RegEx.
Give this regex a try:
/href="([^"]+)/g
Here is a sample of its usage (JsFiddle Demo)
var subject = 'Googlesome other textWikipedia';
var result = subject.replace(/href="([^"]+)/g, 'href="javascript:anyFunction(\'$1\')');
If you give your hrefs unique IDs you can do this:
var val = $("#myHref").attr("href");
$("#myHref").attr("href", "javascript:anyFunction('"+val+"');");
If you want to avoid unique IDs then you can do this (applied to all a's):
​$("a").each(function() {
var val = $(this).attr("href");
$(this).attr("href", "javascript:anyFunction('"+val+"');");
});​​​
If you want to avoid applying this to all hrefs you can give all the hrefs you want changed a class then use a selector like this: $(".hrefToModify")...
NEW:
If you can use javascript, then can you get access to the anchor tag itself? if so:
anchor_element.href = "javascript:anyFunction('" + anchor_element.href + "')";
OLD:
<a id="link1" href="www.google.com">Google</a>
some other text
<a id="link2" href="www.wikipedia.org">Wikipedia</a>
<script>
document.getElementById('link1').addEventListener('click', function(e) {
alert('hello');
e.preventDefault();
return false;
});
</script>

Get a value from an attribute and add it as another attribute?

How can I use jQuery to get a string of text from the onclick attribute and set it as the href attribute.
Here's the fiddle I'm working with: http://jsfiddle.net/MBmt5/
I want to take only TrackPackage.asp?track=95213&ship=OTHER&ShippingMethod=3 from the onclick attribute and prop it to an href attribute
So that it would end up looking like this: http://jsfiddle.net/52Nha/
Unfortunately, I have no idea how to accomplish this. Can anybody help me? Must be compatible with jQuery 1.4.2. Thanks.
Update
Of course I'd begin with:
$(document).ready(function(){
$('span.trackpackagebutton').closest('a').removeAttr('href');
});
​
Ugly but I hope this will help you.
$('a').attr('href',
$('a')[0].getAttribute('onclick')
.replace("window.open('", '').split(',')[0].replace("'", ''))
.removeAttr('onclick');​​​​​​​​​​​​​​​
Working demo - http://jsfiddle.net/MBmt5/5/
Note: Based on your markup structure you can use the right selector and reuse the above code.
E.g: The below code will execute this logic for all the anchors on the page which have onclick attribute which has window.open.
$('a[onclick^="window.open"]').each(function(){
$(this).attr('href',
this.getAttribute('onclick')
.replace("window.open('", '').split(',')[0].replace("'", ''))
.removeAttr('onclick');​​​​​​​​​​​​​​​
});
Here's one way:
http://jsfiddle.net/MBmt5/2/
http://jsfiddle.net/GaZGv/1
var $a = $('span.trackpackagebutton').closest('a');
var href = $a.attr('onclick').split('(')[1].split(',')[0].replace(/'/g, '');
$a.attr('href', href).removeAttr('onclick');
alert(href)​

Remove anchor, but not arguments, via JavaScript

I want to change the following example URL
http://www.mydomain.net/site?argument1=test1&argument2=test2#anchor
to
http://www.mydomain.net/site?argument1=test1&argument2=test2
with JavaScript. How would I best do that?
EDIT: With 'anchor' and the other text elements, I meant generic elements. So the anchor could also be another text. Sorry.
If you're trying to change the current location's anchor, it's better to change window.location.hash:
window.location.hash = '';
In some browsers this will avoid a reload of the page as the URL changes.
Try this:
window.location = window.location.replace(/#anchor/,"");
OK, so I tried this, and it worked perfectly fine:
var url=window.location.toString();
url=url.replace(/#anchor/,'');
window.location=url;
This should replace #anchor but also #anchor_etc or #anchor-etc from your url
var url = "http://www.mydomain.net/site?argument1=test1&argument2=test2#anchor";
url = url.replace(/\#[a-z\-\_]+/i, '');
window.location = window.location.replace('#anchor','');

Remove tag around a text node using javascript

If I have some HTML that looks like this:
<div id="text">
This is some text that is being written <span class="highlight">with
a highlighted section</span> and some text following it.
</div>
And I want to remove the "span" leaving the text node within, how would I go about doing that? I tried using jQuery to do the following:
wrap = $('.highlight');
wrap.children().insertBefore(wrap);
wrap.remove();
But that doesn't work I'm guessing because children returns an empty set since there's only a text node in there. So all that happens is that the span and its contents are removed.
I'm also open to alternatives to my approach here. What's happening is that my code actually creates that span when a user selects a block of text. It wraps the selected text in a span to visually differentiate it. I need to remove the span afterward though because of some quirks with the way mozilla's range object works.
EDIT: I don't want to replace the entire content of '#text' by the way since it could be very large.
You get the text, and replace the span with it:
var wrap = $('.highlight');
var text = wrap.text();
wrap.replaceWith(text);
wrap it in a plugin
(function($) {
$.fn.tagRemover = function() {
return this.each(function() {
var $this = $(this);
var text = $this.text();
$this.replaceWith(text);
});
}
})(jQuery);
and then use like so
$('div span').tagRemover();
Working Demo here - add /edit to the URL to play with the code
This works:
wrap = $('.highlight');
wrap.before(wrap.text());
wrap.remove();
This will do what you want, and also preserve any tags within the .highlight span.
content = $(".highlight").contents();
$(".highlight").replaceWith(content);
element = document.getElementById("span id");
element.parentNode.insertBefore(element.firstChild, element);
element.parentNode.removeChild(element);
text.replace(/</?[^>]+(>|$)/g, "");
it would be much easier to just change the class of the span than to actually remove it. You can use pure javascript:
document.getElementById("span id").className="";
Or jquery's toggleClass function:
$("element").toggleClass("highlight");
Also, best practices say that you shouldn't use class names that imply a style, like highlight. Try "emphasized" instead. :D
A better unwrap plugin:
$.fn.unwrap = function() {
this.parent(':not(body)')
.each(function(){
$(this).replaceWith( this.childNodes );
});
return this;
};
from Ben Alman

Categories