Evidencex
Evidencex

Reputation: 111

How to obtain the text contained in an element ID with jquery

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

Answers (4)

Reinstate Monica Cellio
Reinstate Monica Cellio

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

kasper Taeymans
kasper Taeymans

Reputation: 7026

check out this jsfiddle

working DEMO

var theDiv = $("div[id^=bernar]");

alert('id= ' +theDiv.attr('id'));

Upvotes: 0

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

This should do the trick:

$("div[id^='bernar']").prop("id");

Upvotes: 0

andy
andy

Reputation: 2399

theDiv.attr('id') is what you need to return the full ID string

Upvotes: 2

Related Questions