mathinvalidnik
mathinvalidnik

Reputation: 1600

How can I select element that has specific value for 'abbr' attribute with jquery

Part of my html is :

<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' . How can I accomplish that with jquery?

I tried like this:

$("#row").find("[abbr='selectme']").text() 

but it returns nothing.

Upvotes: 1

Views: 1804

Answers (3)

Maxim Roman
Maxim Roman

Reputation: 135

You can simply search the element by attr name:

$("[abbr='selectme']").text();

Upvotes: 0

Mansoor
Mansoor

Reputation: 763

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. 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

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

nodeType === 3

numeric value "3" is used to get the text nodes. 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".

Here is the working example http://jsfiddle.net/842nn/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

.text() returns the text content of the descendant elements also, filter them out

var text = $("#row").find("[abbr='selectme']").contents().filter(function () {
    //select only text nodes of the targetted td element
    return this.nodeType == 3
}).text();

Demo: Fiddle

Upvotes: 4

Related Questions