Avinash Raj
Avinash Raj

Reputation: 174696

How to get a specific element using jquery?

I'm trying to get the div element which has the class repeat. So I tried this, but it shows undefined.

var data = '<div class="test form-group col-xs-6 repeat" id="repeat_py">\n <div class="kv col-lg-2">index:\n<pre class="num">0</pre></div>\n<div><span class="kv">value: <pre class="num">m</pre></span></div></div>'

alert($(data).find('div.repeat').html())

Fiddle

Upvotes: 4

Views: 178

Answers (6)

smirfan
smirfan

Reputation: 26

ALternate solution:

var data = '<div class="test form-group col-xs-6 repeat" id="repeat_py">\n <div class="kv col-lg-2">index:\n<pre class="num">0</pre></div>\n<div><span class="kv">value: <pre class="num">m</pre></span></div></div>'
$('body').append(data);
alert($('body').find('div.repeat').html());

Fiddle link

https://jsfiddle.net/fgf9nyn0/18/

Upvotes: 0

samumaretiya
samumaretiya

Reputation: 1175

you are just missing wrapper class here that's why you got an error as undefined

try the following code

	var data = '<div><div class="test form-group col-xs-6 repeat" id="repeat_py">\n <div class="kv col-lg-2">index:\n<pre class="num">0</pre></div>\n<div><span class="kv">value: <pre class="num">m</pre></span></div></div></div>'
alert($(data).find('div.repeat').html())

This give me perfect alert

Upvotes: 0

Hitesh Hadia
Hitesh Hadia

Reputation: 1063

You can simply try with this alert($(data).html());

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You need .filter() instead of .find()

Reduce the set of matched elements to those that match the selector or pass the function's test.

 $(data).filter('div.repeat').html()

var data = '<div class="test form-group col-xs-6 repeat" id="repeat_py">\n <div class="kv col-lg-2">index:\n<pre class="num">0</pre></div>\n<div><span class="kv">value: <pre class="num">m</pre></span></div></div>'

alert($(data).filter('div.repeat').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 6

Adam Azad
Adam Azad

Reputation: 11297

Try this

var data = '<div class="test form-group col-xs-6 repeat" id="repeat_py">\n <div class="kv col-lg-2">index:\n<pre class="num">0</pre></div>\n<div><span class="kv">value: <pre class="num">m</pre></span></div></div>';
 
var HTMLobject = $('<div/>').html(data);
console.log(HTMLobject.find('div.repeat').html());
alert(HTMLobject.find('div.repeat').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68373

replace find with filter

alert($(data).filter('div.repeat').html())

find looks for children, filter looks at the sibling level

Upvotes: 1

Related Questions