MKP
MKP

Reputation: 117

Jquery, how to select an element by its first position value of an attribute

In html:

<tr data-s=""></tr>
<tr data-s="1"></tr>
<tr data-s="2 1"></tr>
<tr data-s="3 2 1"></tr>

I'm trying to build a selector in order to get the trs by the value of the first position of data-s attribute.

Thanks in advance.

Upvotes: 0

Views: 174

Answers (5)

Sumit Kumar
Sumit Kumar

Reputation: 11

$('[data-s]').each(function () {
    var test = $(this).attr('data-s')
    if(test != undefined){
        var firstDataValue = parseInt(test.split(' ')[0]);
        /*run you test case for first value and return back this on success */
    }
})

Upvotes: 1

Vinay
Vinay

Reputation: 7676

function customFn(elm,sel)
{
  var tmp = $();
  $(elm).each(function(){
    data=$(this).data('s').toString().split(' ')[0];
    if(data.trim()===sel.toString().trim())
     tmp=tmp.add(this);
  });
  return tmp
}

customFn("tr","3");

https://jsfiddle.net/68x8Leuz/

Upvotes: 1

Ali BARIN
Ali BARIN

Reputation: 1920

You can get the element by first position of data-s attribute as far as I understood.

$('[data-s^="3 "]');

Or if you want to get first position of data-s attribute's value, you can do this;

$('[data-s]').data('s').split(' ')[0];

There is a plunker example for you.

Upvotes: 2

gaetanoM
gaetanoM

Reputation: 42044

My proposal is based on jQuery.filter function:

$(function () {
  var elements = $('table tr').filter(function(index, element) {
    return this.getAttribute('data-s').split(' ')[0] == '1';
  });
  console.log(elements.length);
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<table>
    <tr data-s=""></tr>
    <tr data-s="1"></tr>
    <tr data-s="2 1"></tr>
    <tr data-s="3 2 1"></tr>
</table>

Upvotes: 1

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

You can use .split(" ")[0] to get first value of data-s attribute

$("table tr").each(function() {
    console.log($(this).attr("data-s").split(" ")[0])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table>
<tr data-s=""></tr>
<tr data-s="1"></tr>
<tr data-s="2 1"></tr>
<tr data-s="3 2 1"></tr>
</table>

Upvotes: 1

Related Questions