Reputation: 111
I need to be able to write a javascript function that returns the ID of a specific element as text to the screen without knowing the entire div id. I will only know the first 6 characters of an id, and the last two characters will be two random numbers.
For example:
HTML:
<div id="coe02"></div>
<div id="bernar15"></div>
<div id="mason23"></div>
<div id="wolffe33"></div>
Lets say I wanted to return "bernar15" how would I do that?
Right now I have :
var theDiv = $("div[id^='bernar']");
This returns the correct div, but now I want to obtain the entire id of that element.
Is there a way to do this?
Upvotes: 1
Views: 60
Reputation: 26143
The easiest way is...
var divID= $("div[id^='bernar']")[0].id;
It gets the div using jQuery, as you already had, but then gets the DOM element using [0]
, and gets the id of it.
Upvotes: 2
Reputation: 7026
check out this jsfiddle
working DEMO
var theDiv = $("div[id^=bernar]");
alert('id= ' +theDiv.attr('id'));
Upvotes: 0
Reputation: 21233
This should do the trick:
$("div[id^='bernar']").prop("id");
Upvotes: 0