Home > other >  How can I get the href value from a link to use as value?
How can I get the href value from a link to use as value?

Time:01-05

I have following setup:

<div >
  <div >
    <a href="https://my-link-1.com"></a>
  </div>
  <div >
    <a href="https://my-link-2.com"></a>
  </div>
  <div >
    <a href="https://my-link-3.com"></a>
  </div>
  ... 15 .map-pointer div's in total
</div>

What I want to do is that the content of the a-element will be automatically filled in with the value of the href. Stripped from the https://, the '-' and .com.

So my links will eventually look like this:

<a href="https://my-link-1.com">my link 1</a>
<a href="https://my-link-2.com">my link 2</a>
...

Is this possible with jQuery? I'm not sure where to begin. I know that I first have to store the href attribute in a variable. But how can I do that for all the different links?

CodePudding user response:

Can do something like this:

$("a").each(function() {
     var linkName;
     linkName = this.href.replace("https://", "");
     linkName = linkName.replace(/-/g," ");
     linkName = linkName.replace(".com/", "");
     this.innerHTML = linkName;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <a href="https://my-link-1.com"></a>
  </div>
  <div >
    <a href="https://my-link-2.com"></a>
  </div>
  <div >
    <a href="https://my-link-3.com"></a>
  </div>
</div>

CodePudding user response:

You can try this :

let title = '';
$('.map-container a').map( function() {
    let href = $(this).attr('href');
    title = href.replace('https://', '').replace('.com', '').replaceAll('-', ' ');
    console.log(title)
    $(this).html(title);

}).get();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <a href="https://my-link-1.com"></a>
  </div>
  <div >
    <a href="https://my-link-2.com"></a>
  </div>
  <div >
    <a href="https://my-link-3.com"></a>
  </div>
</div>

  • Related