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
CodePudding user response:
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>
CodePudding user response:
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>