3

I want to loop through all of the paragraph elements in my document and adjust their html. Currently I use some jquery:

console.log("loop through <p> elements");    

$("p").each(function()
{
    console.log("next <p> element with id: " + this.id);
});

However only "loop through paragraph elements" appears in the console and I have a few paragraph elements with unique ids in my body:

<body>
    <p id="para1"> paragraph 1 </p>
    <p id="para2"> paragraph 2 </p>     
    <p id="para3"> paragraph 3 </p> 
</body>

I am hoping it is some kind of syntax error with the .each() loop and that someone can correct me, any help would be much appreciated.

jctwood
  • 131
  • 1
  • 8

4 Answers4

6

You code should be:

$("p").each(function()
{
    console.log("next <p> element with id: " + $(this).attr('id'));
});

Because $(this).id does not exist, or this.id is valid too.

LIVE DEMO

Wilfredo P
  • 3,959
  • 25
  • 44
2

You should use

$("p").each(function() {
    console.log("next <p> element with id: " + this.id);
});

id is a property of Element instances like this. If you wrap it into a jQuery element, it will no longer have the id property, so you will have to get it using jQuery methods like $(this).prop('id'). That is unnecessary, though.

Oriol
  • 225,583
  • 46
  • 371
  • 457
0

jQuery objects do not have an id property. To get the ID of the element, use $(this).attr('id').

If it still does not loop through the tags, then it is probably running before the DOM has a chance to finish loading. Placing your code inside a ready handler will delay execution until the DOM has fully loaded:

$(document).ready(function() {
    console.log("loop through <p> elements");    

    $("p").each(function()
    {
        console.log("next <p> element with id: " + $(this).attr('id'));
    });
});
ElGavilan
  • 5,747
  • 16
  • 24
  • 35
  • I correct it to this and it still only outputs "loop through paragraph elements" as if there are no paragraph elements. Thank you though. – jctwood Dec 15 '14 at 22:20
  • 1
    @jctwood Is your code inside of a ready handler? It may be executing before the DOM is fully loaded, meaning the `

    ` tags aren't even rendered yet.

    – ElGavilan Dec 15 '14 at 22:23
0

Do you get the error: Uncaught ReferenceError: $ is not defined? If this is the case load the JQuery library. Add this on to the Head of your html document.

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Gijs Mater
  • 281
  • 2
  • 5