chrisapotek
chrisapotek

Reputation: 6227

How to select element by its body contents?

I have the following element in my page:

<u>abc123</u>

How to select that element and change its contents 'abc123' to something else?

What I am actually trying to do is adding an iframe in between <u></u>. I know it is kind of silly, but I have a special requirement for that.

A second question: Is it possible to substitute the whole thing (<u>abc123</u>) for the iframe, or the iframe tag must go in between the <u></u>?

Thanks!

Upvotes: 0

Views: 60

Answers (4)

JellyBelly
JellyBelly

Reputation: 2431

try this:

JS

$("u").html('<iframe src="http://www.google.com" width="300" height="300">Alternative context</iframe>');

Upvotes: 0

Genjuro
Genjuro

Reputation: 7735

you can add content to your using the Text() function .

$("u").text(yourText);

for selecting the element by its content

$("u").each(function(i) {
    if ($(this).text()=="abc123"){
     //do what you want
}
   });

Upvotes: 0

You can replace the element with an iframe this way (this is straight JavaScript, but you can do that in jQuery also):

<u id="test"></u>

var e = document.getElementById('test');
var iFrame = [...];

e.parentNode.insertBefore(iFrame, e);
e.parentNode.removeChild(e);

Thanks

Upvotes: 0

Rob W
Rob W

Reputation: 349042

To filter by content (example):

$("u").filter(function(){
    return $(this).text() == "abc123";
}).html("<iframe>");

To directly execute code:

$("u").each(function(){
    var $this = $(this);
    if($this.text() == "abc123"){
        $this.html("<iframe>");
    }
})

Use .replaceWith() instead of .html() if you want to also replace the tags (<u></u>).

The .html() method overwrites the current contents of an element. If you want to add new information without erasing the previous data, use .append().

Upvotes: 2

Related Questions