Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!