Dalhousie
Dalhousie

Reputation: 129

Accessing a hyphenated attribute using a variable

The below syntax works:

hello = $("html").find('[id=foo-var]').html();

But how do we specify "foo-var" through a variable?

var holder = "foo-var";
hello = $("html").find('[id=' + holder + ']').html();

This of course, doesn't work.

Upvotes: 1

Views: 1126

Answers (3)

Sonjoy Samadder
Sonjoy Samadder

Reputation: 77

You can use template literal for better looking syntax

$("html").find(`[id=${holder}]`).html();

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to wrap the attribute value in quotes if it contains a restricted character:

var holder = "foo-var";
var hello = $("html").find('[id="' + holder + '"]').html();

However given that id attributes have to be unique in the DOM you should be using an id selector in the first instance:

var holder = "foo-var";
var hello = $('#' + holder).html();

If you have multiple elements with the same id then that's a separate problem which needs to be addressed in your HTML.

Upvotes: 1

ssilas777
ssilas777

Reputation: 9804

Change the quotes "'"

var holder = "foo-var";
hello = $("html").find('[id="' + holder + '"]').html();

Upvotes: 1

Related Questions