user1937021
user1937021

Reputation: 10791

get the value of an attribute with JQuery

I have the following html, generated with JS.

  <div lang="en" id="s7_videoview_playPauseButton" class="s7playpausebutton" data-description="Scene7ComponentHolder" data-component="PlayPauseButton" state="up" selected="true"></div>

I want to grab the value of the selected attribute when this button is clicked, I'm using this code:

$(document).on('click ', '.s7playpausebutton', function(e) {
    e.preventDefault();
    console.log($(this).attr('selected'))
    $(this).val($(this).attr("selected"));
});

but it always gives me back "selected" and not the actual value ie. true or false. What is wrong?

Upvotes: 0

Views: 95

Answers (1)

Austin Schmidt
Austin Schmidt

Reputation: 316

First, it's useful to note that the selected attribute is traditionally unique to <option> elements, not <div> elements. This causes issues with jquery's $().attr() method. However, good old javascript works as expected. Replacing

$(this).val($(this).attr("selected"));

with

this.getAttribute('selected');

should fix your issue.

Here's a working jsfiddle as well.

Upvotes: 1

Related Questions