ivopetkov / html5-dom-document-php

A better HTML5 parser for PHP.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

allow selecting by $dom->querySelectorAll('article[data-rid]');

WilliamStam opened this issue · comments

so in my use case i need to find all elements with a data attr of data-rid but i dont have the value. might be worth including it officially?

so i basically edited the QuerySelectors.php and changed

 } elseif (preg_match('/^([a-z0-9]*)\[(.+)\=\"(.+)\"\]$/', $selector, $matches) === 1) { // tagname[attribute="value"] or [attribute="value"]
            $result = [];
            $tagName = strlen($matches[1]) > 0 ? $matches[1] : null;
            $walkChildren($this, $tagName, function($element) use (&$result, $preferredLimit, $matches) {
                if ($element->attributes->length > 0 && $element->getAttribute($matches[2]) === $matches[3]) {
                    $result[] = $element;
                    if ($preferredLimit !== null && sizeof($result) >= $preferredLimit) {
                        return true;
                    }
                }
            });
            return new \IvoPetkov\HTML5DOMNodeList($result);
		}

to

 } elseif (preg_match('/^([a-z0-9]*)\[(.+)\=\"(.+)\"\]$/', $selector, $matches) === 1) { // tagname[attribute="value"] or [attribute="value"]
            $result = [];
            $tagName = strlen($matches[1]) > 0 ? $matches[1] : null;
            $walkChildren($this, $tagName, function($element) use (&$result, $preferredLimit, $matches) {
                if ($element->attributes->length > 0 && $element->getAttribute($matches[2]) === $matches[3]) {
                    $result[] = $element;
                    if ($preferredLimit !== null && sizeof($result) >= $preferredLimit) {
                        return true;
                    }
                }
            });
            return new \IvoPetkov\HTML5DOMNodeList($result);
		} elseif (preg_match('/^([a-z0-9]*)\[(.+)]$/', $selector, $matches) === 1) { // tagname[attribute="value"] or [attribute="value"]
			$result = [];
			$tagName = strlen($matches[1]) > 0 ? $matches[1] : null;
			$walkChildren($this, $tagName, function($element) use (&$result, $preferredLimit, $matches) {
				if ($element->attributes->length > 0 && $element->getAttribute($matches[2])) {
					$result[] = $element;
					if ($preferredLimit !== null && sizeof($result) >= $preferredLimit) {
						return true;
					}
				}
			});
			return new \IvoPetkov\HTML5DOMNodeList($result);
		}

```

(copied the first block and changed the match[3] part and removed some stuff from regex

Thank you. I'll include your code in the next couple of days.

v0.5.8 is out now. Thanks again for your contribution.