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.
source to share
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.
source to share
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'));
});
});
source to share