Sumeet Gavhale
Sumeet Gavhale

Reputation: 800

How to Select 'id' attribute of a <div> using jQuery

Sorry if this question is similar to some other questions already asked, but even after searching through those I have not get the expected results.

I have more than 1 div tag in my page like:

<div id='slider1'>&@Slider@&</div>

<div id='slider2'>&@Slider@&</div>

I am using jQuery to select id attribute of a div whoes value will be &@Slider@& as I need the Id for some later purpose.

I have tried using [attribute=value] selector but it isnt working as expected in this case

function showtext() {

    alert($("[text='slider']").prop('id'));

} 

I will be calling this function on some event, the problem is I am getting "undefined" in the alertbox. Where am I going wrong.

Even tried using

function showtext() {

    alert($("[text='slider']").attr('id'));

} 

Still getting same "undefined" result

Thank you in Advance

Upvotes: 2

Views: 1822

Answers (4)

Zafar Ahmad
Zafar Ahmad

Reputation: 428

You can use contains to identify if a div has Slider text in it. I am using a javascript array to accommodate all the ids of the divs. I hope this will work-

<script type="text/javascript">
var divs = [];
$(document).ready(function(){
  $( $("div:contains(Slider)") ).each(function() {
  divs.push($(this).attr('id')));
  });
console.log(divs);
});
</script>

Upvotes: 0

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

You can do it by using.

console.log($("div:contains('Slider')").prop('id'));

Above code only doing first id only, if you want to get all id's, then please try below code

$("div:contains('Slider')").each(function() {
alert(this.id)
});

See this fiddler Demo

Upvotes: 3

Om.
Om.

Reputation: 2682

Use this.

$(document).ready(function(){

  $( $("div:contains(Slider)") ).each(function() {
   alert($(this).attr('id'));
  });

Above code will return list of all matching id of matched div

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388416

You need to use contains selector since you want to test the text content of a div

alert($("div:contains('Slider')").prop('id'));

Your selector $("[text='slider']").prop('id') tries to find an element with attribute text and value slider, something like <div text="slider"></div>

Upvotes: 6

Related Questions