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
My Answer:
Here is the corrected code using jQuery:
javascript
jQuery(document).ready(function(){
var heading_text = '$heading_text';
jQuery('h1, h2, h3, h4, h5, h6').each(function(){
var current_heading = jQuery(this).text();
jQuery(this).text(current_heading + ' ' + heading_text);
});
});
And here is the equivalent code using plain JavaScript:
javascript
document.addEventListener('DOMContentLoaded', function(){
var heading_text = '$heading_text';
var headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
headings.forEach(function(heading){
var current_heading = heading.textContent;
heading.textContent = current_heading + ' ' + heading_text;
});
});
Both of these codes will concatenate the `$heading_text` to the text of all heading tags on the page.
Rate this post
4 of 5 based on 8982 votesComments