Getting the value or text of an HTML attribute using jQuery

print
Grabbing attributes to use in your JavaScript is often handy.  HTML attributes can be used to send various options to your script or attributes used for multiple switches to control different elements of what you are doing.

You can use HTML attributes on their own, or grab them from specific elements with this.

If you are using a standalone element, such as:

<button class="btn btn-outline-success btn-sm buyButton" value="profile" customTitle="Profile Upgrade">BUY</button>

You can use a specific selector:

const itemTitle = $('.buyButton').attr('customTitle');

If you are using multiple selectors, then you can grab the values from the button you want, when using onClick, for example, in a similar way.

So if you have:

<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="profile" customTitle="Profile Upgrade">BUY</button>
</div>
<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="listing" customTitle="Listing Upgrade">BUY</button>
</div>
<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="highlight" customTitle="Highlight Listing">BUY</button>
</div>

(I’ve made some of these up, and some of the bits are unnecessary, like the DIV’s, they are just in the project I’m working on)

So if you want to get the customTitle attribute to use in your logic somewhere, use:

$(".buyButton").on('click', function(e) {
    e.preventDefault();
    const customTitle = $(this).attr('customTitle');
})

 

Share this post:
Related Posts
Only allow numbers to be entered in an HTML form text field
Getting the ID of draggable and droppable elements – jQuery

Leave a Comment