-2

I have a HTML button and I want to add an id to the element. However I'm not able to do it manually, so I'm looking for an option through jQuery.

<div class="mejs-button mejs-playpause-button mejs-play">
  <button type="button" aria-controls="mep_0" title="Play" aria-label="Play" tabindex="0"></button> 
</div>
Cleptus
  • 3,446
  • 4
  • 28
  • 34
M Production
  • 59
  • 1
  • 2
  • 9
  • 1
    But what's the use of adding `id` after the page is loaded? Looks like an XY problem to me. – Praveen Kumar Purushothaman Oct 04 '18 at 15:15
  • This is 100% pointless. If you can select the element in order to put an `id` on it, then you don't need to put an `id` on it as you have already selected it... – Rory McCrossan Oct 04 '18 at 15:17
  • 1
    *"I have a HTML button and I want to add an id to the element."* Why? Sounds like an [X/Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me... – T.J. Crowder Oct 04 '18 at 15:17
  • While this is likely an XY problem, there *are* situations where you might want to add an `id` after the element is created. For instance, if you're creating the elements from HTML text, but the `id` information is coming from an insecure source. In that case, you do want to add the `id` using DOM manipulation (probably just after creating the element, but before adding it to the DOM). You would do so because changing it in the HTML text, prior to creation, would be a security hole. – Makyen Oct 05 '18 at 20:20
  • For example: `let id='from-insecure-source';let newDiv = $('
    '); newDiv.find('button').attr('id', id);` is secure, whereas `let newDiv = $('
    ');` is not. If someone is trying to get code to run, the former might end up with an invalid ID, but the code won't be run.
    – Makyen Oct 05 '18 at 20:33
  • Adding an ID on the fly is useful when you are adding an element on the fly. Of course you know where it is when you are adding it...but knowing where it is at a different time could be problematical. With a unique ID, it's a no-brainer. – Jerry Kaidor Dec 06 '19 at 17:31

1 Answers1

3

You can do it with jQuery using prop() or attr() method :

jQuery(document).ready(function($) {
    $('.mejs-button.mejs-playpause-button.mejs-play button').prop('id', 'my-id');
    //Or 
    $('.mejs-button.mejs-playpause-button.mejs-play button').attr('id', 'my-id');
});

$('.mejs-button button').prop('id', 'my-id');

console.log( $('.mejs-button button').prop('id') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mejs-button mejs-playpause-button mejs-play"><button type="button" 
aria-controls="mep_0" title="Play" aria-label="Play" tabindex="0"></button> 
</div>
Mohammed Acharki
  • 234
  • 2
  • 14