Gianluca Ghettini
Gianluca Ghettini

Reputation: 11678

How to select all the HTML elements having a custom attribute?

I know I can select all the HTML elements with a custom attribute by just doing:

$('p[mytag]')

As you can see, I also need to specify the actual HTML div type (a p element in this case). But what if I need to retrieve all the HTML elements irrespective of their type?

Consider this code:

<p>11111111111111</p>
<p mytag="nina">2222222222</p>
<div>33333333333</div>
<div mytag="sara">4444444444</div>

how I can select the 2 html elements (the p and the div) with custom attribute mytag?

Upvotes: 1

Views: 1463

Answers (2)

Rafael Duarte
Rafael Duarte

Reputation: 569

Use querySelectorAll (javascript) :

document.querySelectorAll('[mytag]');

Or even simpler with jQuery:

$('[mytag]');

Upvotes: 2

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You just need to use $("[mytag]")

console.log($("[mytag]"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>11111111111111</p>
<p mytag="nina">2222222222</p>
<div>33333333333</div>
<div mytag="sara">4444444444</div>

Upvotes: 2

Related Questions