Reputation: 34188
i have many links in page but few links has few specific css class attached. i want to avoid those link which has .noclass attached. the below code solve my problem.
<a href="#" class="noclass">Link with No class1</a><br/>
<a href="#" class="noclass">Link with No class2</a><br/>
<a href="#" >Link without No class</a><br/><br/>
<div id="footer_column6">
<a href="#" class="noclass">Link with No class</a><br/>
<a href="#" class="">Link without No class</a><br/>
<a href="#" class="">Link without No class</a>
</div>
$(document).ready(function() {
var hyperLink = $("a:not(.noclass)");
$.each(hyperLink, function(index, value) {
var href = $(value).attr("href");
//Test code to update the back ground
$(value).css("background-color", "red");
$(value).attr("href", "/" + countrycode + (href == '/' ? '' : href));
href = $(value).attr("href");
});
});
when the scenario is bit different like i want to ignore anything with css class .noclass then above code is not working.
suppose if few links are there in div where noclass has been attached to div and i do not want to iterate links in those div which has no class attached.
so if noclass is attached directly with links or may be noclass may attached to parent like div or span. in this case i do not want to iterate links if its parent has no class attached. so tell me what little modification i have to add in above jquery code.
thanks
Upvotes: 0
Views: 139
Reputation: 2795
I have revised my previous code, I realised there was a logic flaw and also didn't like that it relied on adding an extra outer div to make it work. This version selects all links initially and then from within your .each, it tests if the link as the .noclass or has an ancestor with .noclass:
$(document).ready(function() {
var hyperLink = $("a");
$.each(hyperLink, function(index, value) {
if($(this).hasClass('noclass') || $(this).parents('.noclass').length) {
return;
}
var href = $(value).attr("href");
//Test code to update the back ground
$(value).css("background-color", "red");
$(value).attr("href", "/" + countrycode + (href == '/' ? '' : href));
href = $(value).attr("href");
});
});
This is more robust as it also works with links at the root of the page, and for any kind of wrapper element (div, span, section, article, etc).
Here's a Fiddle example (note, I had to comment out the countrycode line to make the Fiddle work, as countrycode is not defined).
Upvotes: 1