Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dom Manipulation Methods</title>
    <%-- ** What are jquery DOM manipulation methods--%>
    <%-- ** How to set, retrieve, remove attribute values using jquery--%>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        //https://api.jquery.com/category/manipulation/
        // $('div').attr('title')       // displays only the first matching element found
//        $('div').attr('title', 'New DIV Title');        // to set just add second paramenter
        $(document).ready(function () {
            $('div').each(function (i) {
                $(this).attr('title', 'div' + (i + 1) + ' Title');
            });
            $('div').each(function () {
               alert( $(this).attr('title'));
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="div1" title="My DIV1">
        DIV 1
    </div>
    <div id="div2" title="My DIV2">
        DIV 2
    </div>
    </form>
</body>
</html>
Posted
Comments
ZurdoDev 11-Aug-15 15:46pm    
2 alerts come because of $('div').each. The $('div') selects all divs and then you call .each() so it runs for each div in your page.

What is it that you want?
Sergey Alexandrovich Kryukov 11-Aug-15 15:54pm    
Did you try to use JavaScript debugger? :-)
—SA
kellyapt1 11-Aug-15 17:54pm    
As RyanDev has indicated, using $('div').each will pop up an alert for all of the divs on the page. To have an alert for a specific div use the ID of the div like this:

$('#div1').each(function () {
alert( $(this).attr('title'));
});

As mentioned in the comments, you are using .each on your divs so for each div you will get that alert.
 
Share this answer
 
I find out the solution to my problem. ASP.NET add these two input elements within div. This is why it my previous code was picking these extra 2 divs. What I did to solve the issue was wrap my html code within a main div and call $('#main div').each.

XML
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZAWMcFIVrd603vMUvq/dpg+m8qr3" />
</div>
<div>
    <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="EF932D07" />
</div>
 
Share this answer
 
Thank you for your feed back...I understand what the code is supposed to do just return 2 divs, but is returning 4. And the page doesn't have more than 2 divs.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900