Reputation: 99
how to get div class value using dom document
i need to echo this value 4,458 members
from the below code
< div class="mbs fcg">4,458 members< /div>
right now my orginal code is
$links = $dom->getElementsByTagName('div');
foreach ($links as $link){
echo $link->nodeValue;
echo $link->getAttribute('class');
}
how to target this particular class = mbc fcg
?
now with my present code i am getting all div values.
what changes i should do
Upvotes: 0
Views: 4654
Reputation: 1759
you will need to use DOMXPath, which will take a DOMDocument instance
$xpath = new DOMXPath( $dom );
// if the className doesn`t changes
$members = $xpath->query( '//div[@class="mbs fcg"]' );
// if the class name changes ex. class="mbs fcg my-other class-name"
$members = $xpath->query( '//div[contains(@class,"mbs fcg")]' );
alternatively if you want to iterate all over your div`s you could try
$divs = $dom->getElementsByTagName( 'div' );
foreach( $divs as $div ){
// if the className doesn`t changes
if( $div->getAttribute( 'class' ) === 'mbs fcg' ){
echo $div->nodeValue;
}
// if the class name changes ex. class="mbs fcg my-other class-name"
if( strpos( $div->getAttribute( 'class' ), 'mbs fcg' ) !== false ){
echo $div->nodeValue;
}
}
Upvotes: 2
Reputation: 534
NOTICE::: THIS IS A JAVASCRIPT SOLUTION ... NOT A PHP DOMDOCUMENT SOLUTION
Try this HTML:
<div id="ME" class="mbs fcg">4,458 members</div>
... and this Javascript:
var WANTED_TEXT = document.getElementById('ME').firstChild.nodeValue;
EDIT2:
If you actually want, to get all textnodes from all occurrences of elements having class='mbs cfg'
... then try the following HTML:
<div class="mbs fcg">4,458 members</div>
... and this Javascript:
var Collection = document.getElementsByClassName('mbs fcg');
for(i=0; i<Collection.length; i++) {
Texts = Collection[i].firstChild.nodeValue;
document.write('<p>'+Texts+'</p>');
}
That should echo the pure text from all elements in the Collection.
Upvotes: 1
Reputation: 75
I think you need to use an id
to target a single div
, such as:
< div id="my_id_name" class="mbs fcg">4,458 members< /div>
Upvotes: 0