Let's say I have a div:
<div id="mainContent">some random text. bla bla bla.</div>
let's say that the keword in this example is the word random
. how could I place an image on top of that word?
In other words I will have to find that div with JavaScript then use a regular expression to find the keyword and then maybe wrap that keyword inside a span placing an img tag inside with it's position set to absolute.
I guess the hardest part in this is warping the keyword with a span?
moreover how could I place the image on the center of the word? do I have to wrap it on a table instead?
First, store the contents of the div with:
var x = document.getElementById('abc').innerHTML;
Then, use regex to replace the keyword with span wrapped version.
var keyword = "test";
x.replace(keyword, "<span>"+keyword+"</span>");
Then swap it back in;
document.getElementById('abc').innerHTML = x;
I think using this would be better:
x.replace('\b'+ keyword +'\b', "<span>"+keyword+"</span>");
\\b match a word boundary.
For the answer you accepted, you have to know the id of the div that has the keyword. This solution is a bit more dynamic and uses jquery to find all divs with your keyword so you could place images on all of them.
var keyword = "random";
var found = $('div:contains("' + keyword +'")');
$.each(found, function(){
var wrapper = '<span class="whatever">' + keyword + '</span>';
var oldHtml = $(this).html();
$(this).html(oldHtml.replace(keyword, wrapper));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.