Select and display character in more than one div

2

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

ForthisIusethefollowingcode:

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><!--PrimeiroArticleCard--><articleclass="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 while I can display the character in the other% divs% of the page, the code captures the character of only the first .letter .

    
asked by anonymous 01.01.2019 / 01:17

1 answer

3

You need to iterate through the elements. The $('.title').html(); will only catch the first element with the .title class. You can use .each to scroll through all elements .title and get to 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><!--PrimeiroArticleCard--><articleclass="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   if you just get the text, not the element's HTML.

    
01.01.2019 / 01:24