User:Enterprisey/parent-cats.js

Source: Wikipedia, the free encyclopedia.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
$( function () {
	mw.loader.using( [ "mediawiki.api", 'mediawiki.util' ], function () {
		var api = new mw.Api();
		var catsOnPage = mw.config.get('wgCategories');
		for(var cat of catsOnPage) {
			// check if any categories on this page are parents of this category
			api.get({formatversion:2, prop:'categories', titles:'Category:'+cat})
				.then(function(data){
					var parents=data.query.pages[0].categories.map(c => c.title);
					var actualCat = data.query.pages[0].title.substring('Category:'.length);

					for(var catOnPage of catsOnPage) {
						if(parents.indexOf('Category:'+catOnPage) >= 0){
							// tag parent with child
							$('a[href$="Category:' + catOnPage + '"]')
								.css({'background-color':'pink'})
								.text(catOnPage + ' (parent of '+actualCat+')')

							// tag child with parent
							$('a[href$="Category:' + actualCat + '"]')
								.css({'background-color':'pink'})
								.text(actualCat+' (child of '+catOnPage+')')

						}
					}
			});
		}
	});
});