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?
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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With