Prototype Selector: Simple Examples

I am just starting a prototype, before I was on jquery.

I cannot find simple examples on the Internet about how:

  • Selecting all elements with the same identifier on the page (I do this, but it only works for the first element: $('mydiv').hide() )
  • Select a div that is contained in another div by their identifier.
  • hides all elements that have the myClass class.
+4
source share
3 answers

As mentioned above, you should not have the same identifier on the page more than once. Besides being against standards, this is a recipe for potential problems, since you don’t know how your JavaScript will react to it. It uses classes instead.

Selecting all elements having the same id on the page (I do this, but this only works for the first element: $ ('mydiv'). Hide ())

Use $$ :

 $$('.myclass') 

Select a div that is contained in another div by their identifier.

Use $$ :

 $$('div#outer div#inner') 

hides all elements that have myClass class.

Use $$ , each() and hide()

 $$('.myClass').each(function(d) { d.hide(); }); 

$$ is your friend.

+7
source

A few things that I would add.

 $$('.myClass').each(function(d) { d.hide(); }); 

can be replaced by the following:

 $$('.myClass').invoke("hide"); 

Also, be careful with using $$ , on a page with a large dom it is usually faster to orient the parent with $ , and then use select() for your selector

So

 $$('div#outer div#inner') etc.... 

can be rewritten as follows:

 $('parent_of_inner_and_outer').select('div#outer div#inner') etc.... 
+1
source

This is not particularly beautiful, but if you are faced with a situation similar recently, where there may potentially be several elements with the same identifier on the page, and you do not have the ability to change this, then something like this will work. In my case, I at least knew that they were all in span tags.

  var spans = $$('span'); for (i = 0; i < spans.length; i++) { var span = spans[i]; if (span.id == 'add_bookmark_image_' + id) { span.hide(); } if (span.id == 'is_bookmarked_image_' + id) { span.show(); } } 
0
source

Source: https://habr.com/ru/post/1308136/


All Articles