peter
peter

Reputation: 2103

Select Element whose ID is attribute in another Element

How do I select an element whose ID is given in an attribute of another element?

<div id="_News" class="link active" data-wife="News">News</div>

I want to grab the element with the ID given in data-wife. I've tried something like

$("'#" + $(this).attr("data-wife") + "'").show();

but it looks totally wrong to me (and does not work, of course..).

Upvotes: 1

Views: 75

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206347

demo

$('#_News').click(function(){ 
  $('#'+this.dataset.wife).show();  
});

Upvotes: 1

sangram parmar
sangram parmar

Reputation: 8736

Just Syntax Change

$("#" + $(this).attr("data-wife")).show();

Upvotes: 0

Jason P
Jason P

Reputation: 27022

You're doubling up your quotes. You would end up with a selector that was interpreted like this:

$("'#News'")

Try this instead:

$("#" + $(this).attr("data-wife")).show();

As a side note, it's simpler and preferable to use data() to access data- attributes:

$("#" + $(this).data("wife")).show();

Upvotes: 4

Pointy
Pointy

Reputation: 413826

To get the value of "data-" attributes, you can use .data():

$('#' + $(this).data('wife')).show();

Note that you leave off the "data-" prefix. In your code you introduced an extra layer of quotes, which is incorrect. The library just wants a string, not a string with a quoted string in it.

Upvotes: 4

Related Questions