Home > database >  selecting element with dynamically set data-x attribute
selecting element with dynamically set data-x attribute

Time:11-13

i have a video tag which i use for a p2p chat the tag looks like this

<div id="secondary-user">
     <video id="their-video" data-peer="0" autoplay loop autobuffer muted playsinline controls></video>
</div>

i set data-peer chat dynamically when chat start with remote user specific id (peer)

function start_chat( remote_user_id , stream){

            $('#their-video').data('peer' , remote_user_id );    
           // add stream
}

i want to stop the stream of that specific video tag

function stop_chat( remote_user_id ){

      let player = $(`#their-video[data-peer="${remote_user_id }"]`) ; 
      //stop the stream 
}

the problem is selector cant find the element even tho i can see the data-peer is set correctly

enter image description here

the reason i dont want to use only id as selector is sometimes the stream get replaced with new one before i can call stop_chat and i dont want to stop the new stream ... so it's important to use data-peer on the selector

here is the output for

console.log(player.length);
console.log(player);

enter image description here

like @Toufiq Ahmed said using attr to set the value solved the problem ... i wonder why ?!

CodePudding user response:

I tried to recreate this $('#their-video').data('peer' , remote_user_id ); and found that data function doesn't create attribute in element. use jquery attr function insteatd. for setting $('#elemnt').attr('data-peer', 'value') and for getting use $('#elemnt').attr('data-peer')

this way your $(#their-video[data-peer="${remote_user_id }"]) ; work just fine.

  • Related