简体   繁体   中英

Add id's to <p> using JavaScript or jQuery or Angular

I have an HTML document that is dynamically generated.

It has a bunch of <p> tags that have text in it. I am trying to select the <p> when user clicks on that specific text. Unfortunately, I am not allowed to add ids to the <p> tags which I could use to select the specific block of the test.

So I need to find a way to dynamically add id's to the <p> tags using javascript or jQuery or angular.

I have seen some solutions which use jQuery .attr("id", "newId") but it needs a selector and I don't know what to use as a selector.

Can anyone suggest something?

Maybe this helps:

$(function(){
  $("p").on("click", function(){
    $(this).attr('id', 'value');
  });
})

http://plnkr.co/edit/mvKZBopcwuVqAJV7vq7j?p=preview

Assuming all and only the interested p elements are on the page, try this:

jQuery( 'p' ).on( 'click', function() {
  jQuery( this ).attr( 'id', 'yourID' );
} );

Of course you'll need some code to manage progressive ids as they need to be unique on the page.

To be more specific and give an example of making progressive ids, let's say all of your p elements are within a container:

<div id="target_paragraphs">
  <p>...some text 1..</p>
  <p>...some text 2..</p>
  <p>...some text 3..</p>
  <p>...some text 4..</p>
  ...
  <p>...some text n..</p>
</div>

you could use this script:

count = 0;

jQuery( '#target_paragraphs p' ).on( 'click', function() {
  jQuery( this ).attr( 'id', 'paragaraph_ID_' + count );
  count++;
} );

Without looking at your code, we can't really see the problem, but as i understand it you need a click event on all p tags? You can bind the event to all p tags like this: $("p").click(function(event){});

inside the function, this will become the element you clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM