mtk
mtk

Reputation: 13709

Get the text within children nodes using jquery

I have the following html page structure:

<div class="result-row clearfix">
    <span>Name1</span>
    <span>city1</span>
    <span>phone1</span>
    <span>details1</span>
</div>
<div class="result-row clearfix">
    <span>Name2</span>
    <span>city2</span>
    <span>phone2</span>
    <span>details2</span>
</div>
... 
... many such similar divs

And I got simple input field from the user

<label for="name">Name</label> <br />
<input type="text" name="name" autocomplete="off" /> <br />

<label for="city">City</label> <br />
<input type="text" name="city" autocomplete="off" /> <br />

On it's blur event, I would like to make invisible all such div's that does not have the text to be searched and just show the div's that has matched (i.e. the div that has the text within the span tag).

I am not able to retrieve and match this using jquery. I have tried the following:

var nodes = $(".result-row");
console.log("Nodes length: "+nodes.length);  // Displays the correct number of child nodes

for(var i=0;i < nodes.length; i++) {
    var cur = nodes[i];
    console.log(cur);  // Displays '#text' in browser js console log.
    console.log(cur.childNodes[0]);  // Gives undefined. Expecting to get the 1st span tag here.
}

EDIT

I need to display the rows that has the span with matching text. Have updated the html little bit, Please refer to the updated question.

I am able to get the complete data as text of all the span's combined. Is there any way to get the array of spans inside the particular div?

Upvotes: 2

Views: 938

Answers (2)

Ram
Ram

Reputation: 144659

You can use :contains selector:

var $row = $('.result-row');
$('input[type=text]').blur(function() {
    var val = this.value;
    $row.hide();
    $row.has('span:contains("'+val+'")').show()
})

http://jsfiddle.net/x3VtX/

Upvotes: 3

hjindal
hjindal

Reputation: 606

nodes[i] is a jquery object, which doesn't have childNodes property i guess.. so you should be using nodes[i].get(0).childNodes instead...

Upvotes: 1

Related Questions