user826855
user826855

Reputation: 598

Replace HTML Tag Conents

What's the best way to create a function that replaces the contents of HTML elements?

I have looked into using regular expressions for this, but have since found out this method is not really suitable due to permanence issues. PHP needs to keep cycling through the HTML in order to find all/any matches.

I need to create a function that will except to params. One which is the element's tag name () and the other the elements class name (class="someclass")

If a class is set, then I need to replace all elements of that tag and class name set with new content.

If a class hasn't been set, then it should just search for the tag name.

<div>Replace Element Tag Contents</div>
<div class="someclass">Replace Element Contents That uses specified class</div>

Any help is greatly appreciated. Please let me know if this doesn't make sense!

Upvotes: 0

Views: 208

Answers (1)

Josh Frankel
Josh Frankel

Reputation: 198

I would use jQuery unless you specifically need to use php for some reason.

$('div.someclass').text('this will replace the text in all div's with the class someclass').removeClass('someclass').addClass('Your new class name');

I would read this also http://api.jquery.com/text/

If you need to use PHP there is an awesome dom parser that has already been built. http://simplehtmldom.sourceforge.net/

Upvotes: 1

Related Questions