Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way of selecting all html tags that have a specific data-[propriety] regardless of value?

I'm trying to add some kind of on the fly configuration for my require js modules. I declared some html tags like this:

    <header data-module='js/views/header'>

    </header>

    <section data-module='js/views/homepage' data-hash='/'>

    </section>

    <section data-module='js/views/statistics' data-hash='/statistics'>

    </section>

    <footer data-module='js/views/footer'>

    </footer>

And the jQuery query I use in order to get all elements that have data-module set to something different than null is:

            var $viewModules = $('[data-module]');

Is there a more efficient way fo selecting those elements? I never used the data selector in jQuery. Thanks.

like image 205
Vlad Nicula Avatar asked Jan 16 '23 19:01

Vlad Nicula


2 Answers

Since you don't really have a common tagName or className to use to further reduce the search, your current way would be the most efficient way of doing it.

var $viewModules = $('[data-module]');
like image 81
Kevin B Avatar answered Jan 18 '23 08:01

Kevin B


This is a hard one, however, seeing you asked about efficiency, using find() on the document seems slightly faster, by up to 10%.

var $viewModules = $(document).find('[data-module]');

See Test-Results

If I had to take a guess to why it is faster I'd say somehow find is optimized behind the scenes but that is just a guess.

like image 28
Nope Avatar answered Jan 18 '23 08:01

Nope