Search code examples
javascripthtmlhref

Target particular section of href address without jQuery


Firstly,

Is there a way to target a particular section of a href link for use in an if statement?

Essentially how can I target the C section of the following href link:

href="/a/b/c/d/e/index.html";

Secondly,

The desired if statement in JavaScript, best described in words, is:

"If section three contains C, do something."

Lastly,

I want to apply the if statement using the href of each div for the HTML shown below in order to add to the classList of sample:

<div class="a-1" href="/a/b/c/d/e/index.html">
 <a class="location">text</div>
</div>

Solution

  • You can try with split() to generate an array to match the character at specific position:

    var href="/a/b/c/d/e/index.html";
    href = href.split('/');
    if(href.indexOf('c') == 3){
      console.log('Matched at position:', href.indexOf('c'));
    }

    However, if you wish to implement an if statement based on a different href from multiple elements, you need to create an Array that implements forEach, and select which elements you wish to implement classList.add(), as follows:

    var divs = Array.from(document.querySelectorAll("div"));
    
    divs.forEach(function(div) {
      var href = document.querySelector(".a-1").getAttribute("href");
      var location = div.querySelector(".location");
    
       href = href.split("/");
    
       if (href.indexOf("c") == 3) {
         location.classList.add("c");
        }
      })