Reputation: 1361
I have a jQuery function to change the href on a webpage. How do I make this script only run inside the #container
div?
$('a[href*="example.com"]').each(function(){
var index = this.href.indexOf(".com/");
this.href = this.href.slice(0, index+5)
})
I've tried this,
$('#container').$('a[href*="example.com"]').each(function(){
var index = this.href.indexOf(".com/");
this.href = this.href.slice(0, index+5)
})
but it doesn't work. What's wrong with the code above?
Upvotes: 3
Views: 2717
Reputation: 388316
Use .find()
$('#container').find('a[href*="example.com"]').each(function(){
var index = this.href.indexOf(".com/");
this.href = this.href.slice(0, index+5)
})
Or use descendant selector
$('#container a[href*="example.com"]').each(function(){
var index = this.href.indexOf(".com/");
this.href = this.href.slice(0, index+5)
})
You can also try a slightly different version
$('#container').find('a[href*="example.com"]').attr('href', function(idx, href){
var index = href.indexOf(".com/");
return href.slice(0, index + 5)
})
Upvotes: 2