Frage

Using JQuery and/or Javascript how would I do the following -

I need to find the <span> which has a custom attribute equal to a certain value. I then need to set the inner <span> equal to some text.

Example: In the html below, I need to find the span with attribute data-my-custom-attribute == Value1 and fill the inner span with some text.

<span data-my-custom-attribute="Value1" >
    <span>  /**put text here***/  </span>
</span>

<span data-my-custom-attribute="Value2" >
    <span>  /**leave empty***/  </span>
</span>
War es hilfreich?

Lösung

You can use this if the div will always be a sibling of the span with the attribute.

$('#MyDiv').nextAll('[data-my-custom-attribute="ValueX"]:first').find('span').text('something');

After your edit

I guess you only need that :

$('[data-my-custom-attribute="Value1"] span').text('something');

Andere Tipps

Use the css siblings selector ~

$('#MyDiv ~ [data-my-custom-attribute="Value1"] > span').text('BOOH!')

edited for selecting the inner span

$('#MyDiv').siblings('span[data-my-custom-attribute]:first > span').text("text goes here");

Based on your original (and updated) question, either of these methods should work to find the spans:

// works because your custom attribute is a data attribute
$('span').filter(function (i) {
    return $(this).data('my-custom-attribute') === 'Value1';
}).children('span').text('yay! new text');

// works regardless of what the custom attribute is
$('span[data-my-custom-attribute="Value1"]').children('span').text('yay! new text');
// or
$('span[my-custom-non-standardized-html-attribute="Value1"]').children('span').text('yay! new text');

Here's a fiddle demo: http://jsfiddle.net/ucq94/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top