Home > Mobile >  How to automatically detect an HTML tag if it contains a certain attribute?
How to automatically detect an HTML tag if it contains a certain attribute?

Time:09-24

How to automatically detect an HTML tag if it contains a certain attribute like data-wow-delay? This is from wow.js.

What I want to do is that if an HTML tag contains the said attribute, it will automatically add the classes wow bounce in the tag.

Example

HTML
<h1 data-wow-delay="0.2s">
    sample
</h1>
JS (this is where I am at lost, not sure how to start it)
Outcome should be something like this when inspected
<h1
    class="wow bounce"
    data-wow-delay="0.2s"
>
    sample
</h1>

Note: there are a lot of different HTML tags that use this attribute.

CodePudding user response:

Use Element.hasAttribute() to check whether the element contains the specified attribute:

const elem = document.querySelector('h1');

if(elem.hasAttribute('data-wow-delay')){
  elem.classList.add('wow', 'bounce')
}
.wow.bounce{
  background-color:grey;
}
<h1 data-wow-delay="0.2s">
  sample
</h1>

Alternatively, you can use querySelectorAll and the CSS attribute selector to select all elements with the attribute:

document.querySelectorAll('[data-wow-delay]').forEach(e => e.classList.add('wow','bounce'))
.wow.bounce{
  background-color:grey;
}
<h1 data-wow-delay="0.2s">
  sample
</h1>

<p data-wow-delay="0.1s">sample</p>

  • Related