Select and display character in more than one div

Asked

Viewed 34 times

2

I am working on a theme for Ghost and in the display of articles (blog feed) the title of the article and the summary will be displayed as follows:

inserir a descrição da imagem aqui

For this I use the following code:

var getText = $('.title').html();
var sliceText = getText.slice(0, 1);

$(".letter").append(sliceText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Primeiro Article Card -->
<article class="card-article">
  <header class="card-title">
    <h1 class="title">Lorem ipsum dolor sit amet</h1>
    <div class="letter"></div>
  </header>
</article>

<!-- Segundo Article Card -->
<article class="card-article">
  <header class="card-title">
    <h1 class="title">Sed ac vehicula nulla.</h1>
    <div class="letter"></div>
  </header>
</article>

<!-- Terceiro Article Card -->
<article class="card-article">
  <header class="card-title">
    <h1 class="title">Vivamus ac elit a ex pulvinar.</h1>
    <div class="letter"></div>
  </header>
</article>

Basically I get the first character of <h1 class="title"></h1> and the display in <div class="letter"></div>.

The problem is that although I can display the character in the other Ivs .letter page, the code captures the character only of the first <h1 class="title"></h1>.

1 answer

3


You need to iterate the elements. The $('.title').html(); will only take the first element with the class .title. You can use the .each to go through all the elements .title and arrive at the result:

$('.title').each(function(){
   
   var getText = $(this).text();
   var sliceText = getText.slice(0, 1);
   
   $(this)  // elemento da vez
   .closest('header') // procura o ancestral com a tag "header"
   .find('.letter') // procura no ancestral acima a classe .letter
   .append(sliceText); // insere a letra
   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Primeiro Article Card -->
<article class="card-article">
  <header class="card-title">
    <h1 class="title">Lorem ipsum dolor sit amet</h1>
    <div class="letter"></div>
  </header>
</article>

<!-- Segundo Article Card -->
<article class="card-article">
  <header class="card-title">
    <h1 class="title">Sed ac vehicula nulla.</h1>
    <div class="letter"></div>
  </header>
</article>

<!-- Terceiro Article Card -->
<article class="card-article">
  <header class="card-title">
    <h1 class="title">Vivamus ac elit a ex pulvinar.</h1>
    <div class="letter"></div>
  </header>
</article>

Note that I used .text() instead of .html(). It’s more interesting in the case of taking only the text, and not the HTML of the element.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.