user1856596
user1856596

Reputation: 7243

jQuery: Selecting the inner html of an elemnt with a specific value and assign it to a variable?

I have this code:

<dl class="item-options">
    <dt>dt1</dt>
    <dd>dd1</dd>
    <dt>dt2</dt>
    <dd>ss2</dd>
</dl>

Now I want to access the dt1 by its content and assign the value from dd1 to it. I am iterating over all the dds in a each loop, so for each dd I access, I want to get the content from the matching dt.

Any ideas how to do that?

Thanks!

Upvotes: 1

Views: 181

Answers (2)

Darren
Darren

Reputation: 70804

Try:

var it = $(".item-options dt").first().text());

http://jsfiddle.net/hyskp/

If dt1 isn't the first element, you could loop over each dt:

$("dt").each(function(e) {
   var dt = $(this).text();
   if (dt == "dt1") {
     // logic   
   }
});

http://jsfiddle.net/xErBM/

Upvotes: 1

Anthony Grist
Anthony Grist

Reputation: 38345

You can use the :contains selector to select the element(s) that contain specific text, like so:

$('.item-options dt:contains("dt1")')

That would select the <dt> element that has the string "dt1" as part of its text. Note that it's not an exact match, so it would also select elements that contain "dt1" as a substring.

Upvotes: 0

Related Questions