Reputation: 195
Hello I would like to add HTML on to a page once it finds particular text. I have managed to get the position I just can figure out how to add text
$(document).ready(function () {
var position = document.documentElement.innerHTML.indexOf('Gas');
//insert HTML at position
})
Upvotes: 0
Views: 62
Reputation: 43481
So since you already know where to insert, just do
var str = element.innerHtml;
element.innerHTML = str.substr(0, position - 1) + "<b>My HTML</b>" + str.substr(position);
Other way it would be to wrap that text in some element and do .insertBefore()
$(document).ready(function () {
var text = $('.my-text').html();
$('.my-text').html(text.replace(/Gas/, '<span id="my-unique-id">Gas</span>'));
var htmlToInsert = $('<b>', {text: 'Inserted text'});
htmlToInsert.insertBefore('#my-unique-id');
$('#my-unique-id').unwrap();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-text">
Abc def Gas Mesa Bas Ras
</div>
Upvotes: 1