2017-06-23 28 views
0

您好,我希望在找到特定文本後將HTML添加到頁面中。我設法讓我能弄清楚如何添加文本在位置X處插入值

$(document).ready(function() { 

     var position = document.documentElement.innerHTML.indexOf('Gas'); 

     //insert HTML at position 

    })  

回答

1

位置那麼既然你已經知道在何處插入,只是做

var str = element.innerHtml; 
element.innerHTML = str.substr(0, position - 1) + "<b>My HTML</b>" + str.substr(position); 

其他方式這將是包裝在一些元素和文字.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>

+0

Theres a + missing –