通过类名获取DOM元素 [英] Getting DOM elements by classname

查看:42
本文介绍了通过类名获取DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP DOM 我正在尝试获取 DOM 节点中具有给定类名的元素.获取该子元素的最佳方法是什么?

I'm using PHP DOM and I'm trying to get an element within a DOM node that have a given class name. What's the best way to get that sub-element?

更新:我最终将 Mechanize 用于 PHP,它更易于使用.

Update: I ended up using Mechanize for PHP which was much easier to work with.

推荐答案

更新:Xpath 版本的 *[@class~='my-class'] css 选择器

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

所以在我对 hakre 的评论做出回应后,我很好奇并查看了 Zend_Dom_Query 背后的代码.看起来上面的选择器被编译成以下 xpath(未经测试):

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 ')]

所以 PHP 将是:

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

基本上,我们在这里所做的只是对 class 属性进行规范化,这样即使是单个类也以空格为界,而完整的类列表也以空格为界.然后用空格附加我们正在搜索的类.这样我们就可以有效地寻找并只找到 my-class 的实例.

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 .

使用 xpath 选择器?

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.

如果你需要用非常复杂的选择器做很多这样的事情,我会推荐 Zend_Dom_Query 支持 CSS 选择器语法(a la jQuery):

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"]");

这篇关于通过类名获取DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆