Reputation: 1293
I have the following:
<ul style="display: block;">
<li id="deviceTree_3" class="device">
<div class="tree-itemBody ">
<div class="triCheck"</div>
<div class="tree-arrowPlaceholder"></div>
<span class="tree-itemContent">Bath Vanity (na)</span>
</div>
</li>
The idea is to get the number after the deviceTree_#
The issue im running into is the number can be various lengths ie ....583 or 3
is this a regex situation or is there something a simpler solution
Upvotes: 0
Views: 135
Reputation: 10378
var tempname=$("#deviceTree_3").attr("id").split("_");
alert(tempname[1]);//show 3
reference split
Upvotes: 5
Reputation: 167
Just $("#deviceTree_3").attr("id").split("_")[1]
.
Simple and sweet
Upvotes: 0
Reputation: 12870
As others pointed out, you can use split
to get the part of the id after _
. You don't need jQuery here. A function taking an element with an id of the form [anything]_[number]
could be:
function numberFromId(domElem) {
var idParts = domElem.id.split("_");
return idParts[1] ? idParts[1] : null;
}
I included this code in this fiddle
Upvotes: 0
Reputation: 756
Reference: http://api.jquery.com/attribute-starts-with-selector/
If you want to get all li
elements that has deviceTree_NNNN
as ID
, using jQuery
you can do the following:
$.each( $("li[id^='deviceTree_']"), function () {
var id_parts = $(this).attr("id").split("_");
console.log( id_parts[1] );
});
For a single li
:
var id_parts = $("li[id^='deviceTree_']").attr("id").split("_");
console.log(id_parts[1]);
Upvotes: 0
Reputation: 22847
The following regex will extract numeric part from any id, no matter if it's on begin or on end or in the middle:
id = 'fda_335534'
var reg = /(?![0-9])*([0-9]+)/
var match = reg.exec(id)
console.log(match[1])
The plus is, it's working for any id structure.
If the id starts always with 'deviceTree_', and there's nothing after the num, just do:
console.log(id.replace('deviceTree_',''))
Upvotes: 0
Reputation: 1722
If your number value is always behind the _
you can get it by
var numberTag = $('#deviceTree_3').attr('id').split('_').pop();
Upvotes: 1
Reputation:
If the format is always "deviceTree_" followed by the number then you can use the below:
var id = document.getElementsByClassName('device')[0].id;
var idNum = id.substring(id.indexOf('_')+1,id.length);
console.log(idNum);
Upvotes: 1