Jquery/Javascript使用自定义属性查找最接近的范围并更改内部html
使用JQuery和/或Javascript,我将如何执行以下操作- 我需要找到Jquery/Javascript使用自定义属性查找最接近的范围并更改内部html,javascript,jquery,innerhtml,Javascript,Jquery,Innerhtml,使用JQuery和/或Javascript,我将如何执行以下操作- 我需要找到,它的自定义属性等于某个值。然后我需要将内部设置为一些文本 <span data-my-custom-attribute="Value1" > <span> /**put text here***/ </span> </span> <span data-my-custom-attribute="Value2" > <span>
,它的自定义属性等于某个值。然后我需要将内部
设置为一些文本
<span data-my-custom-attribute="Value1" >
<span> /**put text here***/ </span>
</span>
<span data-my-custom-attribute="Value2" >
<span> /**leave empty***/ </span>
</span>
示例:在下面的html中,我需要找到属性数据为my custom attribute==Value1的span,并用一些文本填充内部span
<span data-my-custom-attribute="Value1" >
<span> /**put text here***/ </span>
</span>
<span data-my-custom-attribute="Value2" >
<span> /**leave empty***/ </span>
</span>
/**在这里输入文本***/
/**留空***/
如果div
始终是具有该属性的span
的兄弟,则可以使用此选项
$('#MyDiv').nextAll('[data-my-custom-attribute="ValueX"]:first').find('span').text('something');
编辑后 我想你只需要:
$('[data-my-custom-attribute="Value1"] span').text('something');
使用css同级选择器
~
$('#MyDiv ~ [data-my-custom-attribute="Value1"] > span').text('BOOH!')
编辑用于根据原始(和更新的)问题选择内部span,这些方法中的任何一种都可以找到span
s:
// 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');
这里有一个小提琴演示:你说的“最近”是什么意思?您发布的标记中的两个示例与
#MyDiv
的距离(祖先树)相同……也许我不需要“最近的”。我将更改示例。我喜欢~use,但这将删除找不到“最近”的内部空格,它将找到与选择器匹配的所有(后续)元素。OP完全更改了问题的内容,现在所有答案都完全失去了意义