Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find all class, ID, Attribute, and tag in Document #200

Open
mizanexpertofficial opened this issue Jun 18, 2023 · 1 comment
Open

Find all class, ID, Attribute, and tag in Document #200

mizanexpertofficial opened this issue Jun 18, 2023 · 1 comment

Comments

@mizanexpertofficial
Copy link

mizanexpertofficial commented Jun 18, 2023

Hey I try to find all class, id, attr, and tag in document.

Here is example in DOMDocument

Possible to do it via DiDOM?

 //get dom document
$dom = new \DOMDocument();
$dom->xpath = new \DOMXPath($dom);

//setup used selectors array
$this->used_selectors = array('tags' => array(), 'ids' => array(), 'classes' => array());

//search for used selectors in dom
 $classes = array();
     foreach ($dom->getElementsByTagName('*') as $tag) {

     //add tag
    $this->used_selectors['tags'][$tag->tagName] = 1;

     //add id
      if ($tag->hasAttribute('id')) {
        $this->used_selectors['ids'][$tag->getAttribute('id')] = 1;
      }

      //store tag classes
      if ($tag->hasAttribute('class')) {
          $class = $tag->getAttribute('class');
          $tag_classes = preg_split('/\s+/', $class);
            array_push($classes, ...$tag_classes);
        }
 }

//add classes
$classes = array_filter(array_unique($classes));
if ($classes) {
      $this->used_selectors['classes'] = array_fill_keys($classes, 1);
 }
@scott8035
Copy link

What is not working for you? It's certainly possible to do this.

The "class" (and "style") attributes are handled specially by src/DiDom/Element.php. You can modify the "store tag classes" section like so:

//store tag classes
foreach ($tag->classes()->getAll() as $class ) {
    $this->used_selectors['classes'][$class]++;
}

I think that will do what you want for that part. Not sure what you were looking for otherwise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants