[英]How can I select element that has specific value for 'abbr' attribute with jquery
Part of my html is : 我的部分HTML是:
<tr id="row">
<td abbr='selectme'>
<div>Texti inside the div</div>
Text outside the div
</td>
<td>
any others I dont care about
<td>
</tr>
And I am trying to select "Text outside the div" which is inside the td that has attribute 'selectme' . 我试图在具有'selectme'属性的td中选择“div之外的文本 ” 。 How can I accomplish that with jquery?
我怎样才能用jquery来实现呢?
I tried like this: 我试过这样的:
$("#row").find("[abbr='selectme']").text()
but it returns nothing. 但它什么也没有回报。
The reason you are getting nothing in return is probably because you you have to wrap it in a 你得到任何回报的原因可能是因为你必须把它包装成一个
$( document ).ready(function() {}); or $(function(){});
Because div needs to be loaded in the DOM before you reach it through jquery otherwise you are accessing an element which is not loaded yet. 因为div需要在通过jquery到达之前加载到DOM中,否则您正在访问尚未加载的元素。 So by using this code:
所以通过使用此代码:
$(function () {
alert($("#row").find("[abbr='selectme']").text());
});
you will get the following text: Texti inside the div Text outside the div 您将获得以下文本:div内的文本div中的文本
Now as you want to only get the text "text outside the div" which is plain text without wrapped in any tag you have to use .contetns().filter() function and to get where the 现在,因为你只想获得文本“div之外的文本”,这是纯文本而不包含在任何标记中,你必须使用.contetns()。filter()函数并获取
nodeType === 3
numeric value "3" is used to get the text nodes. 数值“3”用于获取文本节点。 so you final code will look like this (I am using alert for illustration)
所以你最终的代码看起来像这样(我使用警报说明)
// Shorthand for $( document ).ready()
$(function () {
// getting the specific text and saving into a variable
//getting the contents of the target element
var myText = $("#row").find("[abbr='selectme']").contents()
// using the filter to get the text node
.filter(function () {
return this.nodeType === 3;
//getting the final text
}).text();
alert(myText);
});
Now when you run the programme you will get the output "Text outside the div". 现在,当您运行程序时,您将获得输出“div之外的文本”。
Here is the working example http://jsfiddle.net/842nn/ 这是http://jsfiddle.net/842nn/的工作示例
您只需按attr名称搜索元素即可:
$("[abbr='selectme']").text();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.