Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
Changing all the heading tags at once using jQuery

So I'm using jQuery to concatenate a string to all the heading tags i.e. h1, h2,...., h6 and display it on the screen. I just want help in the replacing part and if you have a solution in plain javascript, it will be useful too.

This my code which I'm certain is wrong:

        jQuery.noConflict();  
        jQuery(document).ready(function(){
            
            var heading_text = '$heading_text';
            var page_heading = jQuery('h1','h2','h3','h4','h5','h6').text();

            //concatenating the two variables
            page_heading.html(page_heading+' '+heading_text);
        });

here, $heading_text is the input received. for eg: if $heading_text is xyz and text between h1 tag is oh then after calling out this function, the text between h1 tag should be oh xyz

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

elems = $('h1, h2, h3, h4, h5, h6');
heading_text = ' some text';
elems.each(function(){
  text = $(this).text();
  $(this).text(text + heading_text);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>h1</h1>
<h2>h2</h2>
<h3>h3</h3>
<h4>h4</h4>
<h5>h5</h5>
<h6>h6</h6>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the .text(function) overload to append text, however this will replace any html within the header. The alternative is to .append() new content to each header.

As jQuery works on collections, there's no need for any loops:

var heading_text = '$heading_text';

$('h1,h2,h3,h4,h5,h6').append(" " + heading_text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>H1 <i>italic</i></h1>
<h3>H3</h3>

Same, but using .text()

var heading_text = '$heading_text';

$('h1,h2,h3,h4,h5,h6').text((i, txt) => txt + " " + heading_text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>H1 <i>italic</i></h1>
<h3>H3</h3>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda