Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text in a div where find something

I have a div with id content. I want to search in this div My Company and then add after My Company the trade mark ® symbol anywhere it appears in the div id=content. The problem is the text My Company isn't always in HTML as My Company. It could be My <span style="something">C</span>ompany or My <font color="something">C</font>ompany and I don't know how to add the ® symbol after the text My Company even if it contains html tags in (as above).

I want to do this with JS/Jquery. Thank you so much!!!

Tried:

$("#content").each(function() {
    var text = $(this).text();
    text = text.replace("My Company", "My Company®");
    $(this).text(text);
});

but it works only if it is My Company NOT when it is My <span style="something">C</span>ompany or My <font color="something">C</font>ompany

EDIT

I have one (single) div #content

EXAMPLE

<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi et nisl quam. Praesent semper enim elit, vel imperdiet ipsum vulputate ac. Curabitur lacinia vitae metus sit amet consectetur.

My Company

Sed metus risus, iaculis a erat id, pretium congue nisi. Phasellus tempor, massa lobortis scelerisque pharetra, orci metus ultrices quam, eu sodales massa erat ut ipsum. Vestibulum ullamcorper interdum pretium. My <span style="color: orange;">C</span>ompany Praesent mollis in ex in feugiat. Ut vitae placerat diam. 
</div>
like image 822
MM PP Avatar asked Nov 01 '22 00:11

MM PP


2 Answers

Use classes if you want to have multiple divs with the same style on the page.

$("#content").each(function() {
    var text = $(this).html();
    text = text.replace(/My Company/g, "My Company<sup>®</sup>");
    text = text.replace(/My (<\/?span[^>]*>C\<\/span\>ompany)/g, "My Company<sup>®</sup>");
    text = text.replace(/My (<\/?font[^>]*>C\<\/font\>ompany)/g, "My Company<sup>®</sup>");
    $(this).html(text);
});
like image 150
NETCreator Hosting - WebDesign Avatar answered Nov 11 '22 08:11

NETCreator Hosting - WebDesign


This is how you can do it

$(function(){
$('#content').each(function() {
    var text = $(this).text();
    $(this).text(text.replace('My Company', 'My Company®')); 
});

});

EDIT:

May be thi updated code will work if you want to preserve the HTML as well

$(function(){
    var children = $('#content').children();
    children.each(function() {
    var text = $.trim($(this).text());
        if(text === 'My Company'){
            var getTagName = $(this).prop("tagName");
             var tagName = getTagName.toLowerCase();
             var replaceText = '<'+tagName+'>'+'My  Company®'+'</'+tagName+'>';
        $(this).html(replaceText); 
        }
       });
});

Check out the UPdated Fiddle http://jsfiddle.net/69sv52y2/16/

like image 26
Abhinav Avatar answered Nov 11 '22 07:11

Abhinav