Reputation: 598
I have the following HTML.
<div class="red">Div One</div>
<div class="green">Div Two</div>
<div class="blue">Div Three</div>
What's the best way of replacing the text in the div with the green class?
Also, I need a way of retrieving the contents of a tag by element name (), or element name and class ().
Thanks for your help!
Upvotes: 1
Views: 5226
Reputation: 10529
You can use some kind of HTML parser. I'd use DOMDocument or phpQuery.
In the edge case, you can use regex. But I do not recommend this to you!
$html = preg_replace('~(<div class="green">)(.*)(</div>)~', '$1Replacement$2', $html);
if you want to use class green optional, use
$html = preg_replace('~(<div( class="green">|>))(.*)(</div>)~', '$1Replacement$4', $html);
Upvotes: 3
Reputation: 298
jQuery can do it for you
$(".green").empty().html("your new content for div");
and to retrieve content
var content=$(".blue").html(); //retrieves content inside class blue
Upvotes: 2