Get Element by Classname with Domdocument() Method

Get Element by ClassName with DOMdocument() Method

I finally used the following solution :

    $classname="blockProduct";
$finder = new DomXPath($doc);
$spaner = $finder->query("//*[contains(@class, '$classname')]");

How is it possible to get elements by class name in PHP (DOM selectors)?

Use DOMXPath with a custom XPath query. See How can I find an element by CSS class with XPath?

Getting DOM elements by classname

Update: Xpath version of *[@class~='my-class'] css selector

So after my comment below in response to hakre's comment, I got curious and looked into the code behind Zend_Dom_Query. It looks like the above selector is compiled to the following xpath (untested):

[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]

So the PHP would be:

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

Basically, all we do here is normalize the class attribute so that even a single class is bounded by spaces, and the complete class list is bounded in spaces. Then append the class we are searching for with a space. This way we are effectively looking for and find only instances of my-class .


Use an xpath selector?

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

If it is only ever one type of element you can replace the * with the particular tagname.

If you need to do a lot of this with very complex selector I would recommend Zend_Dom_Query which supports CSS selector syntax (a la jQuery):

$finder = new Zend_Dom_Query($html);
$classname = 'my-class';
$nodes = $finder->query("*[class~=\"$classname\"]");

PHP: Getting DOM elements by classname

You can use XPath to easily achieve it.

$page = file_get_contents('http://www.example.com/test');
$doc = new DOMDocument();
$doc->loadHTML($page);

$xpath = new DomXPath($doc);

$nodeList = $xpath->query("//div[@class='inner text-inner']");
$node = $nodeList->item(0);

// To check the result:
echo "<p>" . $node->nodeValue . "</p>";

This will output:

bla bla bla

Javascript: How to get only one element by class name?

document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array-like HTMLCollection returned.

var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];

Else, if you really want to select only one element. Then you need to use 'id' as conceptually it is used as an identifier for unique elements in a Web Page.

// HTML
<div id="myElement"></div>

// JS
var requiredElement = document.getElementById('myElement');

How to get element by class name?

The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.

The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:

var y = document.getElementsByClassName('foo');
var aNode = y[0];

If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:

var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);

As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:

  • querySelector(all)
  • getElementsByClassName
  • Don't use w3schools to learn something
  • Refer to MDN for accurate information


Related Topics



Leave a reply



Submit