1

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?

Gianluca Ghettini
  • 11,129
  • 19
  • 93
  • 159

2 Answers2

2

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>
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
2

Use querySelectorAll (javascript) :

document.querySelectorAll('[mytag]');

Or even simpler with jQuery:

$('[mytag]');
Rafael Duarte
  • 569
  • 6
  • 21
  • `$('[mytag]');` only selects the first element. `document.querySelectorAll('[mytag]');` works though. – Danmoreng Jul 30 '19 at 15:40
  • @Danmoreng No, that's incorrect. `$('[mytag]')` will select them all – j08691 Jul 30 '19 at 15:41
  • I got fooled by taking this for jquery... https://stackoverflow.com/questions/22244823/what-is-the-dollar-sign-in-javascript-if-not-jquery – Danmoreng Jul 31 '19 at 08:26