How can I go through all <p> elements?

I want to loop through all paragraph elements in my document and adjust their html. I am currently using 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 multiple 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 hope this is some kind of syntax error in the .each () loop and someone can fix me, any help would be much appreciated.

+3


source to share


4 answers


The code should be:

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

      



Because it $(this).id

doesn't exist, either this.id

.

LIVE DEMO

+6


source


You must use

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

      



id

is a property of Element

instances of the type this

. If you put it in a jQuery element, it no longer has a property id

, so you will have to use it with jQuery methods like $(this).prop('id')

. It's not obligatory.

+2


source


JQuery objects have no property id

. To get the id of an item use $(this).attr('id')

.

If it still doesn't go through the tags, then it is probably running before the DOM can finish loading. Placing code inside a ready-made handler will delay execution until the DOM is fully loaded:

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

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

      

0


source


Are you getting the error: Uncaught ReferenceError: $ is not defined? If so, download the jQuery library. Add this to the header of your html document.

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

      

0


source







All Articles