0

I want to assign unique ids to paragraphs in a HTML file.
How do i do this using loops in a JavaScript? (assuming that I know the number of paragraphs in it)

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        function count() {
            var num = $("p").size();
            for (var i = 0; i < num; i++) {
                $ "p".innerhtml();
                $id = i;
                I dont know
                if this is right.is this how we assign ids ?
            }
        }
    </script>
</head>

<body>
    <h1>Count paragraphs</h1>
    <div>
        <p>This is paragraph 1.</p>
        <p>This is paragraph 2.</p>
        <p>This is paragraph 3.</p>
        <p>This is paragraph 4.</p>
    </div>
    <form action="">
        <input type="button" value="count" onclick="count()"></input>
    </form>
</body>

6 Answers 6

2

jsBin demo

JavaScript

var elP = document.querySelectorAll("p");  
[].slice.call(elP).forEach(function(el, v) {
    el.id = el.id || "p"+v;    // or use `el.id = "p"+v;` to overwrite
});

jQuery

$("p").prop("id", function(idx, currID) {
    return currID || "p"+idx; // or use `return "p"+idx;` to overwrite
});

The above uses the idx, currID (index, value) arguments of the .prop() method callback
and it will assign an ID pN (N starting from 0) to all your <p> without overwriting an existing ID.

Before:

<p></p>
<p></p>
<p id="foo"></p>
<p></p>

After:

<p id="p0"></p>
<p id="p1"></p>
<p id="foo"></p>
<p id="p3"></p>

P.S: </input> is an illegal closing tag. (See: Void elements)

Sign up to request clarification or add additional context in comments.

1 Comment

clean and simple solution
1

Try using .each() and the .prop() methods together like:

function count() {
        $('p').each(function(index){
           if($(this).prop('id') === ""){ // make sure that we're not overwriting any already assigned id
               $(this).prop('id', 'para-'+index); // index starts at 0
           }
        });
}

Valid id's cannot be just numbers, so i have prefixed them with the phrase "para-"

4 Comments

You should know that typeof $(this).prop('id') will return "string" having your element an ID or not. Don't use jQuery where you don't need to. jQuery is JS so knw your properties and use this.id.
@RokoC.Buljan we only want to add an id when there isnt one. if theres no id it returns "undefined". totally agreed about only jquery when needed. The question appeared to be asking how to do it using jquery however :)
@haxxxton can you please post an example where an element that has no ID will return typeof $(this).prop('id') == "undefined" >> true? Also you can find some nice suggestions about a good use of DOM properties here.
@RokoC.Buljan my bad, i had been using .attr('id') in my testing, and then changed to .prop('id') later without checking that it was different. You are correct. it is .attr('id') that returns "undefined"
0
function count() {
        var par = document.getElementsByTagName('p');
        for (var i=0,j=par.length;i<j;i++) {
            par[i].setAttribute('id',i);
        }
    }

Comments

0

Here:

    count = function() {
            $('div > p').each(function(index, el){
            el.id = 'para-'+index;
            });
    };

The > is used for direct child. You don't have to worry about a p inside a p becaue it's illegal.

http://jsfiddle.net/mirohristov/ywadbga0/1/

5 Comments

Would this not create duplicate IDs if the <p> elements had separate parents? Also, not to forget - IDs can not start with a number.
Well it's specific for his code... he'll get the point. One can always use 'div > p'. Agreed about the name
p inside a p is invalid anyway ;)
Don't make functions valuable global unless you want real issues in the future.
@miro, I meant more if it were <div><p><p></div><div><p></div> - But don't worry, @RokoC.Buljan explained it in this comment: stackoverflow.com/questions/27914671/…
0

Try this:

function count() {
    $('p').each(function(index) {
        this.id = 'p' + index;
    });
}

This will basically cycle through all the 'p' elements. In the context of the function given to the each function, this represents the HtmlElement. You can assign the id directly. There is no need to wrap the HtmlElement in a jQuery object since the id can be accessed on the raw element.

JsFiddle (You will have to inspect the Html in the result to see the ids)

3 Comments

But it would still create duplicate IDs if the <p> elements had separate parents wouldn't it?
I tried adding a <p> with under a separate parent and it didn't assign duplicate ids unless I'm misunderstanding what you're saying
@thePav No, cause the index i argument represents the index inside the returned jQuery each collection. Though the .each() iterator is not needed at all cause $('p') is already a collection of elements so you can go immediately for .prop()
-1

I didnt get if you want innerHTML or id attribute, but i'll do it in both ways.

HTML

<h1>Count paragraphs</h1>
<p></p>
<p></p>
<p></p>
<button onclick='countParagraphs()'>Count it!</button>

Javascript ( with Jquery )

function countParagraphs() {
    var count = 0;
    $("p").each( function() {
        count ++;
        $(this).html( "This is paragraph " + count ).attr( "id", count );
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.