2

I need a bit of help getting the values from these HTML elements with jQuery;

<ul class='post-meta'>
<li><span class='post-meta-key'>uniqueidA:</span> value1</li>
<li><span class='post-meta-key'>uniqueidB:</span> value2</li>
</ul>

These are dynamic values and I need to say get 'value1' from 'uniqueidA' and 'value2' from 'uniqueidB'

2
  • 1
    Consider using <span class='post-meta-value'> Commented Mar 22, 2011 at 17:14
  • if its uniqueidA (ie a unique identifier) why not use the same thing as an id attribute ? <li id="uniqueidA"><label>uniqueidA:</label><span>value1</span></li> and then use $("#uniqueidA").children().filter('span').text() Commented Mar 22, 2011 at 17:21

5 Answers 5

5
var a = $(".post-meta-key:contains('uniqueidA')").get(0).nextSibling.nodeValue;
var b = $(".post-meta-key:contains('uniqueidB')").get(0).nextSibling.nodeValue;

alert(a +" "+ b);

See it on jSFiddle: http://jsfiddle.net/jay2S/

If you need the values without any whitespace you can use jQuery.trim()

alert($.trim(a) +" "+ $.trim(b));

There may be more factors in your particular situation, but this is a quick and dirty way to get it done.

Sign up to request clarification or add additional context in comments.

1 Comment

Smart. nextSibling is a text node in this context.
0

Selectors won't help much here.

You will have to select the parent: $('.post-meta-key:contains('uniqueidA'))

Then you will have to write your own javascript to parse the contents. Or you can copy the parent to a temporary object, then .remove() the span, leaving you with a space and your value.

As Šime Vidas suggests, re-write your HTML so a selector will work directly.

Comments

0

well, why dont put the value text inside a tag with a specific id? could it be an option for you?

<ul class='post-meta'>
    <li><span class='post-meta-key'>uniqueidA:</span><span id="uniqueidA">value1</span></li>
    <li><span class='post-meta-key'>uniqueidB:</span><span id="uniqueidB">value2</span></li>
</ul>

does it solve your problem?

Comments

0

A definition list would better suit your requirements:

<dl class='post-meta'>
    <dt>uniqueidA</dt> <dd>value1</dd>
    <dt>uniqueidA</dt> <dd>value2</dd>
</dl>

... then just use next() to jump to the value.

Comments

0

To get the uniqueid and value, we need to grab both the text() and nodeType values.

var x = $('.post-meta-key');
var y = $('li').contents().filter(function() {
    return this.nodeType == 3
});
alert(x.eq(0).text() + " " + y.eq(0).text()); //This will get you only the first `<li>`

To get the value of all <li>'s we need to create a for loop. See working example below.

Check working example at http://jsfiddle.net/3CcjF/1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.