skip to Main Content

I want to reuse breadcrumbs structure for a friendly SEO category header. How can I get separator (/) in the output using .text() function?

Thanks in advance!

$(function(){
    var str = $( ".breadcrumb-element").text();
    $( "p.text22" ) .html( str );
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="breadcrumb">
    <a class="breadcrumb-element" href="#" title="Go to Sale">Sale</a>
    <a class="breadcrumb-element" href="#" title="Go to Accessories">Accessories</a>
    <a class="breadcrumb-element" href="#" title="Go to Scarves">Scarves</a>
</div>

<br><br><br><br>

<p class="text22"></p>

2

Answers


  1. You can use a function in .text() to check the index of the element and if its not the 1st element, insert a / in front of the text.

    $( ".breadcrumb-element").text(function(i, t){
    str += i == 0 ? t : '/' + t;
    });
    

    JSFiddle

    var str = '';
    $( ".breadcrumb-element").text(function(i, t){
    str += i == 0 ? t : '/' + t;
    });
    $( "p.text22" ) .html( str );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="breadcrumb">
    <a class="breadcrumb-element" href="#" title="Go to Sale">Sale</a>
    <a class="breadcrumb-element" href="#" title="Go to Accessories">Accessories</a>
    <a class="breadcrumb-element" href="#" title="Go to Scarves">Scarves</a>
    </div>
    
    
    <br><br><br><br>
    
    <p class="text22"></p>
    Login or Signup to reply.
  2. Well, this is something for CSS.
    Just define :after pseudo element to display the delimiter.

    Example:

    .breadcrumb-element:after {
      content: '/';
      padding: 0 5px;
    }
    
    .breadcrumb-element:last-child:after {
      content: '';
    }
    

    Using JS for this is little bit bloated. But just my 5 cents.

    .breadcrumb-element {
      text-decoration: none;
    }
    
    .breadcrumb-element:after {
      content: '/';
      padding: 0 5px;
    }
    
    .breadcrumb-element:last-child:after {
      content: '';
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    
    <div class="breadcrumb">
    <a class="breadcrumb-element" href="#" title="Go to Sale">Sale</a>
    <a class="breadcrumb-element" href="#" title="Go to Accessories">Accessories</a>
    <a class="breadcrumb-element" href="#" title="Go to Scarves">Scarves</a>
    </div>
    
    
    <br><br><br><br>
    
    <p class="text22"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search