HTML:
< p class="link-panel ">http:..www.google.com< /p ><br>
< a target="blank" href="">GO< /a>
jQuery:
var linkVal = new Array();
$('.link-panel').each(function(index){
linkVal[index] = $(this).text();
});
$('a').each(function(){
$(this).attr("href", linkVal);
});
I'm trying to get the text value from the P tag and append it to the href attribute in the link. I can do this for one, but I can't seem to work out how to make this work when there is more than one URL?
Thanks
You can iterate over the anchors and get the text from the previous paragraph
$('a').attr('href', function() {
return $(this).prev('p').text();
});
or iterate over paragraphs and set the href for the following anchor
$('.link-panel').each(function() {
$(this).next('a').attr('href', $(this).text());
});
Related
I'm searching a web page for keywords from an array. This code works by replacing text with a tag which highlights the text, but when it finds keywords that are links then it breaks them because it puts a <span> tag within the <a> tag.
I tried to refer to the parent element by changing $this.html() to $this.parent.html() but this didn't work. Here's the JSFiddle: https://jsfiddle.net/uzfsjqyr/1/
I'd appreciate some help, please?
var regex = /(Apples|oranges)/g;
$('*').each(function() {
var $this = $(this);
var text = $this.text();
if (regex.test(text)) {
$this.html(
$this.html().replace(regex, '</a><span style="background: #fa7373;">$1</span>')
);
}
});
You should be selecting all p and a tags in the body instead of using * which will even select the script tag itself. Also, remove the </a> that is closing any anchor tag. To not modify the HTML of anchor tags, you can check that the current element has no children before replacing.
var regex = /(apples|oranges)/g;
$('body a, body p').each(function() {
var $this = $(this);
var text = $this.text();
if (text.match(regex) && $this.children().length===0) {
$this.html(
$this.html().replace(regex, '<span style="background: #fa7373;">$1</span>')
);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
I bought some apples.
</p>
<p>
I bought some oranges.
</p>
<p>
I bought some pears.
</p>
Remove </a> from your code. This </a> is closing any anchor tag.
var regex = /(apples|oranges)/g;
$('*').each(function() {
var $this = $(this);
var text = $this.text();
if (regex.test(text)) {
$this.html(
$this.html().replace(regex, '<mark>$1</mark>')
);
}
});
I'm trying to replace multiple links but only the first one is replaced,
all the other remain the same.
function rep(){
var text = document.querySelector(".link").querySelector("a").href;
var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
document.querySelector(".link").querySelector("a").href = newText;
}
Any suggestions?
It's multiple a href links inside .link elements which I'm talking about.
Your mistake is in using querySelector, so document.querySelector(".link").querySelector("a") literally translates to: get me the first a inside the first .link;
Use querySelectorAll; and you can combine the two selectors:
Vanilla JS:
[].forEach.call(document.querySelectorAll('.link a'), function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
Or, since you'll select items more often, a little utility:
function $$(selector, ctx){
return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}
$$('.link a').forEach(function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})
Or in jQuery:
$('.link a').each(function(){
this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
This doesn't use JQuery, and I've changed your regular expression to something that made more sense for the example. It also works when you run the snippet.
function rep() {
var anchors = document.querySelectorAll(".link a");
for (var j = 0; j < anchors.length; ++j) {
var anchor = anchors[j];
anchor.href = anchor.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
rep();
a[href]:after {
content: " (" attr(href)")"
}
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
Edit: Expanded example showing multiple anchor hrefs replaced inside multiple link classed objects.
Edit2: Thomas example is a more advanced example, and is more technically correct in using querySelectorAll(".link a"); it will grab anchors in descendants, not just children. Edited mine to follow suite.
If you intend to only select direct children of link class elements, use ".link>a" instead of ".link a" for the selector.
Try using a foreach loop for every ".link" element. It seems that
every ".link" element have at least 1 anchor inside, maybe just one.
Supposing every .link element has 1 anchor just inside, something like
this should do:
$('.link').each(function(){
// take the A element of the current ".link" element iterated
var anchor = $(this).find('a');
// take the current href attribute of the anchor
var the_anchor_href = anchor.attr('href');
// replace that text and achieve the new href (just copied your part)
var new_href = the_anchor_href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/,'http://google$2com');
// set the new href attribute to the anchor
anchor.attr('href', new_href);
});
I did't test it but it should move you to the way. Consider that we
could resume this in 3 lines.
Cheers
EDIT
I give the last try, looking at your DOM of the updated question and using plain javascript (not tested):
var links = document.getElementsByClassName('link');
var anchors = [];
for (var li in links) {
anchors = li.getElementsByTagName('A');
for(var a in anchors){
a.href = a.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
I suggest to read the following post comment for some cooler methods of looping/making stuff foreach item.
How to change the href for a hyperlink using jQuery
Is it possible to take the text inside of an <a> tag and add it to title attribute of that tag using JavaScript?
For example:
Hello
I want the text "hello" to be the title attribute to the <a> tag. Like this:
Hello
Can this be done with JavaScript? Any help or direction would be appreciated.
In javascript, as requested:
var anchors = document.getElementsByTagName('a');
for(i = 0;i < anchors.length; i++) {
anchors[i].title = anchors[i].textContent;
}
http://jsfiddle.net/spencerooni/z97rc/
If you have an ID for the specific tag (e.g. ...):
$('#atag').attr('title', $('#atag').text());
or if you'd like to do this for all a tags:
$('a').each(
function() {
$(this).attr('title', $(this).text());
}
);
DEMO
$('a').each(function() {
var $this = $(this); /* slight optimisation over using $(this) twice */
$this.attr('title',$this.text());
});
In the most simple jQuery form:
$('a').attr('title', function(){ return $(this).text() })
jsFiddle example
So I ran up onto a problem, how would I add text into the HTML attachment href. So, and example:
...
How would I change it too:
...
But, what if I had mutiple of these with different href's:
...
...
...
How would I change them all?
href is called an attribute, and you can use .attr() to change it
If you want to add same prefix to all of them then
jQuery(function () {
$('a').attr('href', function (i, href) {
return 'http://google.com' + href;
});
})
Demo: Fiddle
First find all the elements you wish to change and put them into an array (below, I'm just using all anchor tags, but you could do getElementsByClassName and give them all some class as to not affect every anchor tag on the page), then loop through them and append the code.
(function () {
var anchors = document.getElementsByTagName("a");
for (var x = 0; x < anchors.length; x++) {
anchors[x].href = "http://google.com" + anchors[x].href;
}
})();
If you're appending the same string to the start of all anchor tags' HREF attribute within a particular DIV or other container (say it has ID myDiv), that's relatively easy:
$('#myDiv a').each(function(){
$(this).attr('href', 'http://google.com' + $(this).attr('href'));
});
I have a div with id="images".
The div contains some images that are each wrapped in an anchor tag with no target attribute.
I'd like to insert script into my page that pulls a reference to each of these anchor elements and ads a target="new" attribute to them (in the runtime) so that when they are clicked they each open in a new window.
I don't want to hardcode the target attributes on the anchor tags. This is a post deployment workaround. I'm not using jquery in this application.
<div id="images"><img src="foo.png" />...etc </div>
No jQuery required! You can do this easily using native DOM methods:
// Find all the anchors you want to modify
var anchors = document.getElementById('images').getElementsByTagName('a'),
i = anchors.length;
// Add the target to each one
while(i--) anchors[i].target = "new";
You can traverse all the anchor elements inside your div, first by looking up the div itself, and then you can use the element.getElementsByTagName method:
var imagesDiv = document.getElementById('images'),
images = imagesDiv.getElementsByTagName('a');
for (var i = 0, n = images.length; i < n; i++) {
images[i].target = "_blank";
}
function replaceAllAnchors(Source,stringToFind,stringToReplace){
//sample call: body=replaceAllAnchors(body,'<a ','<a target="_blank" ');
var temp = Source;
var replacedStr="";
var index = temp.indexOf(stringToFind);
while(index != -1){
temp = temp.replace(stringToFind,stringToReplace);
replacedStr=replacedStr+temp.substr(0,temp.indexOf("/a>")+3);
temp=temp.substr(temp.indexOf("/a>")+3);
index = temp.indexOf(stringToFind);
}
replacedStr=replacedStr+temp;
return replacedStr;
}
Why can't you use jQuery? I've added this here for other people who google.
It's 1 line of code in a loop:
$('#images a').each(function(){ $(this).attr('target', '_blank'); });
Now isn't that much more simple? Use jQuery if you can.