1

I want to use jQuery to find a link and hide it . I want to search for the text of the link using jQuery. This doesn't work:

<a href="example.com/foo-bar">a website link</a>
function replace_text() {
  var linkText = jQuery('a').text();
  var answer = linkText.replace('a website link', '');
}
replace_text();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Haddly
  • 79
  • 1
  • 2
  • 9

1 Answers1

4

To hide the element by it's text you could use the :contains selector, then hide(), like this:

$('a:contains("a website link")').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com/foo-bar">a website link</a>

Note that the above is a case-insensitive greedy match. If you want an exact match you can use filter(), like this:

$('a').filter(function() {
  return $(this).text().trim() == 'a website link';
}).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com/foo-bar">a website link</a>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • $('a:contains("a website link")').hide(); works when i use the Chrome dev tools but not when i add it to my js file. Can the fact that !important is used have any effect here? – Haddly Apr 10 '17 at 08:52
  • Nope. That sounds more like you aren't including your JS code at the right time. Make sure you execute the above code within a document ready handler, eg `$(function() { /* code here... */ });` – Rory McCrossan Apr 10 '17 at 09:10
  • I did this. Could there be any other reason it doesn't work? – Haddly Apr 10 '17 at 09:23
  • There's plenty, but hard to tell exactly without seeing a working example of your code. Try checking the console for errors – Rory McCrossan Apr 10 '17 at 09:25
  • I added a console.log message and it appears in the dev tools for that page – Haddly Apr 10 '17 at 09:29
  • to give the real example here: the page is https://www.apis.de/unternehmen/kontakt/map/ and the text i want to hide is 'Map by Fla-shop.com' – Haddly Apr 10 '17 at 09:29
  • Right - you've got two issues here. Firstly, the issue is because that text is added after the page loads - hence the above code has no effect. You need to run the code when the map has fully loaded. Secondly, what you're doing is most likely illegal. You're trying to remove the link to the content creator. I suggest you pay for the full version of the software instead of trying to subvert their system. – Rory McCrossan Apr 10 '17 at 11:02
  • Ok. I see, I hadn't thought of any legal issues. I will have to look into that further. – Haddly Apr 10 '17 at 14:32