0

I'm working on an old school app. It's so old that it doesn't support jquery. Which is fine in most cases, but I've run into a spot where it is annoying the hell out of me.

I need to select a link with the word 'Novedades' in it so I can change around the http attribute. Wish I could do this a different way, but they have a CMS is changing everything every way I turn. :) Can you tell I love this system?

Normally, this is how I would write it in Jquery. Simple enough, but how can I turn the find into plain javascript?

var blog = $('.navbar-nav').find('a:contains(Novedades)');

So obviously this would start with

var blog = document.getElementsByClassName("navbar-nav")

Any help would be appreciated! :)

zazvorniki
  • 3,512
  • 21
  • 74
  • 122
  • 1
    Selecting based on text content is less than idea. However, if there's no other way, I'd just use `document.querySelectorAll()` with a single selector to get the `'.navbar-nav a'` elements, then filter them down by testing the `.textContent` of each element. –  Mar 20 '17 at 15:26
  • @squint Yeah, I don't like selecting text either, but this is an awful system. Not quite sure I know where you're going with that though. Something like document.querySelectorAll('navbar-nav a').textContent('Novedades') ? – zazvorniki Mar 20 '17 at 15:29
  • Almost. The `querySelectorAll` method returns a collection. It sounds like you only need to perform a single operation, so the simplest, most broadly compatible way would be to use a `for` loop to iterate the collection, check the `.textContent` property of each individual element, and then change the `href` in the loop. –  Mar 20 '17 at 15:30
  • @zazvorniki you should manually create a function that loops through the `` tags and checks its content. Like the link I posted earlier. that's one way to do it – SrAxi Mar 20 '17 at 15:31
  • If you're only supporting modern browsers, or can transpile the code, there's nicer syntax available. –  Mar 20 '17 at 15:31

1 Answers1

1

Building on squint's comment, you'll have to get old school and loop through them:

var blog = document.querySelectorAll(".navbar-nav a");
for (var i=0;i<blog.length;i++){
   var thisBlog = blog[i];
   var txt = thisBlog.textContent.toLowerCase();
   if (txt.indexOf('novedades') > -1){
      //do your thing
   }
}
mr.freeze
  • 13,731
  • 5
  • 36
  • 42
  • Looks good to me, though it could be less verbose without those single-use variables. An in emulating `:contains()`, it should remain case sensitive. `if (blog[i].textContent.indexOf('Novedades') > -1){` –  Mar 20 '17 at 15:34
  • 1
    Gotcha, was being intentionally verbose for clarity. – mr.freeze Mar 20 '17 at 15:35
  • Thank you very much! You saved me from banging my head against the desk! – zazvorniki Mar 20 '17 at 15:42