Tim
Tim

Reputation: 583

jQuery function only inside a specific div ID

I have the following function that I only want to run inside <div id="imgWrapper">

I have tried a few things with parent but I cannot seem to figure this out.

 <script type="text/javascript" language="javascript">
    $(document).ready(
        function () {
            $("img").each(function () {
                var src = $(this).attr("src");
                if (src.substring(0, 1) == "/")
                    $(this).attr("src", "http://serverName.com/" + src.substring(1))
            });

        }
     ); 
 </script> 

Upvotes: 1

Views: 631

Answers (3)

gdoron
gdoron

Reputation: 150263

If you put space in the selector it's a descendant-selector:

$(document).ready(
    function () {
        $("#imgWrapper img").each(function () { // <<<<<<<=======
            var src = $(this).attr("src");
            if (src.substring(0, 1) == "/")
                $(this).attr("src", "http://serverName.com/" + src.substring(1))
        });

    }
 ); 

descendant-selector docs:

Description: Selects all elements that are descendants of a given ancestor.

Upvotes: 1

Jorge
Jorge

Reputation: 18237

without see your html change this $(img) for $("div#imgWrapper img") or $("img", 'div#imgWrapper')

Upvotes: 0

cebarrett
cebarrett

Reputation: 29

To select just the img elements that are descendants of the imgWrapper div, change this line:

$("img").each(function () {

to this:

$("#imgWrapper img").each(function () {

Upvotes: 0

Related Questions