Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make jQuery function run only inside a specific div id or class

Tags:

jquery

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?

like image 757
Herry Kusmadi Avatar asked Aug 14 '26 16:08

Herry Kusmadi


1 Answers

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)
})
like image 178
Arun P Johny Avatar answered Aug 16 '26 14:08

Arun P Johny