Skip to content

Commit d6236f6

Browse files
committed
Added htmldoc::tag() to enable the tag name to be retrieved from the first item in a collection.
Added tests.
1 parent 8ee0a0b commit d6236f6

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/htmldoc.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -463,12 +463,26 @@ public function parent() : htmldoc {
463463
return $doc->collection($nodes);
464464
}
465465

466+
/**
467+
* Retrieves the tag name from the first tag object in the collection
468+
*
469+
* @return ?string The name of the tag, or null if there are no tags in the collection
470+
*/
471+
public function tag() : ?string {
472+
foreach ($this->children AS $item) {
473+
if (\get_class($item) === 'hexydec\\html\\tag') {
474+
return $item->tagName;
475+
}
476+
}
477+
return null;
478+
}
479+
466480
/**
467481
* Retrieves the specified attribute value from the first tag in the collection or update the attribute on all matching tags
468482
*
469483
* @param string $key The name of the attribute to retrieve
470484
* @param string $value The value of the attribute to update
471-
* @return string The value of the attribute or null if the attribute doesn't exist
485+
* @return ?string The value of the attribute or null if the attribute doesn't exist
472486
*/
473487
public function attr(string $key, ?string $value = null) : ?string {
474488
foreach ($this->children AS $item) {

tests/findHtmldocTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,16 @@ public function testCanTraverseElements() {
103103
}
104104
}
105105

106+
public function testCanReadTagNames() {
107+
$doc = new htmldoc();
108+
if ($doc->open(__DIR__.'/templates/find.html')) {
109+
$this->assertEquals('div', $doc->find('.find')->tag());
110+
$this->assertEquals('p', $doc->find('.find__paragraph')->tag());
111+
$this->assertEquals('h1', $doc->find('.find__heading')->tag());
112+
$this->assertEquals(null, $doc->find('.find__nothing')->tag());
113+
}
114+
}
115+
106116
public function testCanReadAttributes() {
107117
$doc = new htmldoc();
108118
if ($doc->open(__DIR__.'/templates/find.html')) {

0 commit comments

Comments
 (0)