简体   繁体   中英

How to change javascript for loop criteria? Newbie question

Javascript newbie here, just trying to tweak this bit of code. It checks for all HTML elements with a title attribute and adds the class 'tooltipParent'.

I'd like it to only add the class to elements with a title attribute AND the class 'tooltip'. I think I need to add something to the for loop to check for this extra class?

// loop through all objects with a title attribute
var titles=$('[title]');

// use an efficient for loop as there may be a lot to cycle through
for(var i=titles.length-1;i>-1;i--){

   // titled object must be position:relative
   $(titles[i]).addClass('tooltipParent');

}

Thanks!

You can put the class requirement into your original selector:

$('*.tooltip[title]').addClass('tooltipParent');

This means

  • select all elements ( * )
  • with the class "tooltip" ( .tooltip )
  • and a title attribute set ( [title] )
  • and add the class tooltipParent

You can extend your jQuery selector on the first line to select the proper elements. Look at the jQuery documentation for help. It's probably something like var titles = $('.tooltip[title]') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM