snehoozle
snehoozle

Reputation: 273

Search for text in web page that spans multiple div tags using javascript

I'm building an extension that will search a web page for a particular piece of text and insert a tiny photo after the text. If the text is contained within a div tag, these seems fairly easy. Simply use the following:

:contains(text)

However, if the text spans multiple div tags, I'm a little perplexed as to how to proceed...Perhaps I can iteratively search?

Upvotes: 1

Views: 547

Answers (2)

guest271314
guest271314

Reputation: 1

Try

var text = "def"
, img = "<img src=imageurl />";
$("div:contains("+ text +")")
.html(function(_, o) {
    return o.replace(new RegExp(text, "i"), text + img)
})

var text = "def"
, img = "<img src=http://lorempixel.com/20/20/>";
$("div:contains("+ text +")")
.html(function(i, o) {
    return o.replace(new RegExp(text, "i"), text + img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>abc</div>
<div>abc</div>
<div>def</div>
<div>abc</div>
<div>def</div>

Upvotes: 1

Danon
Danon

Reputation: 2972

If you're using jQuery, you could check for children of found element, like:

var $div = $("div:contains(text)");
while (true) {
  var $children = $div.children("div:contains(text)");
  if ($children != []) {
    $div = $children;
  } else {
    break;
  }
}
$div.append( // insert your image here

Update: You could also replace My text with <span>My text</span> (i.e. using Regular expression or whatsover)

and then

<style>
    span::after {
        display: inline;
        content: '';
        width: 32px;
        height: 32px;
        background: url("myimage.png");
    }
</span>

Upvotes: 0

Related Questions