Reputation: 110
I've scoured for ways to do this, I'm probably just missing something very obvious, and for that I am sorry.
I'm trying to add two characters to a h2
element. Which I have done, but if I do more than one h2
the first one is copied. I would like the unique innerHTML of each h2
to have these characters added before and after.
I am aware I could do this with css but I already have before and after on the element doing other things.
$(window).on("load", function() {
// On page load, add greater than and less than signs to all h2s
var regH2 = $('h2').html();
$('h2').html( '<' + regH2 + '>' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2>header1</h2>
<h2>header2</h2>
Upvotes: 1
Views: 699
Reputation: 2239
My answer uses CSS instead of JS:
h2:before { content:'<'; }
h2:after { content:'>'; }
<h2>header1</h2>
<h2>header2</h2>
This renders the content with "<" and ">" even before your page has loaded completely.
If :before and :after is already in use, consider adding extra elements like this:
h2 span:before { content:'<'; }
h2 span:after { content:'>'; }
<h2><span>header1</span></h2>
<h2><span>header2</span></h2>
For me I alway weep when static content is added via JS. ;)
Upvotes: 0
Reputation: 67207
Try to use the callBack
function of .html()
,
$(window).on("load", function() {
$('h2').html(function(_,regH2){
return '<' + regH2 + '>';
});
});
In the above code, regH2
will receive the old html string every time.
Upvotes: 1
Reputation: 25352
Try like this
$('h2').each(function(){
var regH2 = $(this).html();
$(this).html( '<' + regH2 + '>' );
});
Upvotes: 2