How to check if link is present on a page with Jquery? - javascript

I have this link on my web page:
Terms and conditions
I want to use Jquery to check whether this specific link is present or not on the web page. I know how to check if text is present on a page, but am struggling a little with links. If it helps, it is only the terms-conditions-mywebsite bit that I need to use (as mywebsite changes depending on who is using the site).
The class is footer so I have tried $('.footer:contains("terms-conditions") but this doesn't seem to work. Any pointers would be appreciated, thanks so much :)
Edit: I need to check that the actual specific contents of this links is present, rather than the text 'Terms and conditions'

You should check the value of href attribute. You can use Attribute Contains Selector [name*=”value”] which select elements that have the specified attribute with a value containing a given substring:
The following should work:
if($('a[href*=terms-conditions]').length){
//exist
}
OR: Check the link string directly
if($('a:contains("Terms and conditions")').length){
//exist
}

I would look at doing this with Javascript, as it's very straightforward and means you are not reliant on JQuery should you wish to remove JQuery from the site at a later date.
// get <a> elements
var links = document.getElementsByTagName('a');
// loop through each <a>
for (var i = 0; i < links.length; i++) {
// get each href
var hrefs = links[i].getAttribute("href");
// check href against the one you want
if (hrefs == "https://www.google.com") {
// check content of link
console.log('link content:', links[i].innerHTML)
}
}

Related

change part of a link with javascript in a specific div only

Hi I need to edit some links on a page. Using the below code works but causes other problems on the page. I need the code to only affect elements with a certain input id. I also can't just replace the links as a query will be dynamically added to the end of each link. So in summary i just need to replace parts of all links with an input id "btnViewDetails". Any help would be great I'm very stuck. Cheers
<script language="javascript">
document.body.innerHTML = document.body.innerHTML.replace(/JobSeekers/g,'mobile');
document.body.innerHTML = document.body.innerHTML.replace(/JobPositionDetail.aspx/g,'JobPositionDetail_Mobile.aspx');
</script>
var someVariable = document.getElementsByClassName('btnViewDetails');
(you should use class instead of ID, if it is not a unique value).
someVariable is now an array holding all elements with class name btnViewDetails.
Now replace the text you want to replace only on the href values of you elements (you will have to loop over them):
for (i = 0; i < someVariable.length; i++) {
someVariable[i].href // do your replaces here
}

Change the class of a hyperlink depending on its text

I'm trying to set up a web page that contains links to pages that have Disqus comments on them. There is specific guidance on adding a comment count to a link that Disqus provides, but it's not great. You are limited to using an <a> element, and it replaces the text of the hyperlink with new text.
So, if I create a hyperlink like this on my site:
linktext
after the page loads, it looks like this:
<a class="link-processed" href="http://mysite.com/posts/1234#disqus_thread">
(1 and 0)
</a>
(note that, by default, the replacement text would be "1 comment and 0 reactions" but I have modified the default text to return just the numbers, in brackets.)
When the text of the hyperlink is "(0 and 0)" I'd like to hide the link. When it is anything else, I'd like to replace the text of the link with an image link (little speech bubble or similar.)
I am thinking that the way to do this might be to use a couple of classes. I'll apply the first class (hidelink) by default, and use javascript to apply the second class to the <a> element.
However, now I'm stuck. Javascript is not my native domain. This seems like it should be a straightforward task, though?
What are your browser requirements? If you're using IE8+ (or most other browsers) you could use querySelectorAll or getElementsByClassName to get all processed links and then check if its text match your condition:
var elems = document.querySelectorAll('.link-processed');
for(var i = 0, size = elems.length; i < size; i++)
{
if(elems[i].innerText === "(0 and 0)")
{
//0 and 0. Do something
}
}
Alternatively, if you're using jQuery, you could simply select all elements that contain "0 and 0", using the pseudo class :contains:
$("a:contains('0 and 0')")

Make links in a specific div open in new tab

I want to open links in my post on a new page or a new tab rather. But only the link in the specific division, not all the links on my page. I don't wanna put _blank in all my tags it's too time consuming. How can I do that?
Thanks in advance.
With jQuery, you could set the target to _blank for all your links. E.g.
$(function(){
$("#myDiv a").attr("target","_blank");
});
Example on jsFiddle.
You really ought to put them in. If it's too time-consuming, try using a simple regex to do it for you (only run it on the html you care about). Replace:
(<a href[^>]*)(>)
with
$1 target="_blank"$2
If you really need to, you can use JavaScript, but it won't work where javascript is disabled. It's really a terrible solution for this problem:
var el = document.getElementById('myDiv'); // or some other way of making `el` point to your element
var links = el.getElementsByTagName('a');
for( var i = 0; i < links.length; i++ )
{
links.target = '_blank';
}
Here is a link to the Javascript that I use to set all the links within a certain div (or all links which are labeled with a certain class) to open in a new window: http://icode4you.net/use-javascript-to-open-all-links-within-a-certain-div-in-a-new-window.
I originally found this script at http://www.dynamicdrive.com/dynamicindex8/newwindow3.htm

javascript - remove element/node with no ID and specific content

I'm struggling to decipher a way to remove several specific href elements which contain no IDs and are children of individual parents with no IDs.
The best I can manage is identifying the four offending, out of 8 or 9 href tags (and the number may vary), by a specific word within the URL itself. For this, I do the following:
<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
if(ptn.exec(xx[i])){
alert(xx[i]);
}
}
</script>
Of course all this gives me is the four specific URLs within the href where "=media" is present. Now, somehow, I need to be able to remove either these href elements, or their parent elements (which happen to be unordered list tags). It's not until I get a level higher (table cell) that I gain access to an element ID, or anything distinguishing besides a particular word within the URL itself.
I'm open to any approach at this point - PHP may be an option (I really haven't explored this yet), but for this, javascript was my first logical choice. I can't tamper with the page that generates the links directly, only a secondary page which gets included at page load time.
Any pointers on how to solve this??
======================== final solution =====================
<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
while(ptn.exec(xx[i].href)){
alert(xx[i]);
xx[i].parentNode.removeChild(xx[i]);
}
}
</script>
You don't need the ID to remove an element. You only need a reference to the element (which you seem to have).
instead of this:
alert(xx[i]);
try this:
XX[i].parentElement.removeChild(xx[i]);
You can call removeChild() on the parent element, like so:
xx[i].parentNode.removeChild(xx[i]);
As a side note, your regular expression isn't being executed on the href property. Change your if statement to:
if(ptn.exec(xx[i].href)){
var parent = xx[i].parentNode;
parent.removeChild(xx[i]);
http://www.onlinetools.org/articles/unobtrusivejavascript/chapter2.html has some nice examples of similar operations (scroll down).

How to get "raw" href contents in JavaScript

I am trying to write a GreaseMonkey script in which I want to find all of the links that are relative links. It seemed to me that the way to do that would be to match the contents of href against /^https?:///.
But I find that when I access the anchor's href attribute, it's always normalized or cooked into a form that contains "http". That is, if the HTML contains:
<a id="rel" href="/relative/link">inner</a>
accessing
document.getElementById("rel").href
returns
http://example.com/relative/link
How can I access the raw data in the href attribute?
Alternately, is there a better way to find relative links?
Try the getAttribute method instead.
Typical. I figured it out myself almost immediately after posting the question.
instead of:
anchor.href
use:
anchor.getAttribute("href")
Of course, it took me longer to type in this answer than it took everyone else to answer it. (Damn, you people are fast.)
Here's a code snippet you could run to test.
const anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let hrefFullPath = anchor.href;
let hrefRelativePath = anchor.attributes.href.value;
console.log('hrefFullPath', hrefFullPath);
console.log('hrefRelativePath', hrefRelativePath);
}
Let's say, you are at http://localhost:4200, and this is your document as you have shown in the question.
<a id="rel" href="/relative/link">inner</a>
This anchor's attribute value of href is:
document.getElementById('rel').attributes.href.value => /relative/link
And anchor's href value is:
document.getElementById('rel').href => http://localhost:4200/relative/link
I hope it helps.
Get the link dom and add attributes for same and append the actual link to same.
var hrefUrl = 'https://www.google.com/';
const link: HTMLLinkElement = dom?.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('id', 'seo');
dom?.head?.appendChild(link);
dom?.getElementById('seo')?.setAttribute('href', hrefUrl);
// working
Hope this will work for dynamic links that to append for each dynamic pages under js / ts.

Categories