Reputation: 71
I have a strange issue, I'm using jQuery to append some HTML to an h1 tag. I'm using a CMS here at work that I don't have access to the backend, so I have to do some trickery to make things work. My code I'm using is...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var html = '<span style = "font-size: 10pt; font-style: italic; display: block;">Tools to help make your farm profitable and successful</span>';
$('.mainContent h1').first().html(html); });
</script>
Now I've tested this script on jsfiddle and it works just fine, it appends to the H1 tag and everything looks proper. When the actual page loads it, however, it's treating the entire html variable as a string and it's actually printing out the HTML (tags and all) instead of rendering it as you'd expect.
You can see what I mean here
I've attempted many different variations of it, but still can't seem to get it to work on the page. Any ideas? Thank you in advance.
Upvotes: 0
Views: 1025
Reputation: 653
Have you tried using document.createElement()
to create your span
tag? Something like:
<body class="mainContent">
<h1></h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var el = document.createElement('span');
el.style.cssText = "font-size: 10pt; font-style: italic; display: block;";
el.innerHTML = "Tools to help make your farm profitable and successful";
$('.mainContent h1').first().html(el);
});
</script>
</body>
Upvotes: 0
Reputation: 208032
You can try and sneak around the CMS' encoder by using plain vanilla JavaScript for most of the code:
var elem = document.createElement('span');
elem.setAttribute("style","font-size: 10pt; font-style: italic; display: block");
elem.innerHTML = 'Tools to help make your farm profitable and successful';
$('body').append(elem);
Upvotes: 0
Reputation: 25091
Your CMS is likely interfering when it detects the angle brackets in the string. Here's an alternate way of creating DOM elements with jQuery which doesn't use any angle brackets:
$(function() {
var span = $(document.createElement('span')).text('Tools to help make your farm profitable and successful').css({
display: 'block',
fontSize: '10pt',
fontStyle: 'italic',
});
$('.mainContent h1').first().empty().append(span)
});
The above should work, assuming you want to eliminate the text Become Ag Savvy
from the page.
If you want to keep it, and merely append the new span to it, delete the call to .empty()
.
This is, of course, entirely contingent on the CMS keeping the <script>
tags intact (and not converting them to <script>
).
Upvotes: 1