Mohsin Patel
Mohsin Patel

Reputation: 226

how to find first level of child tag in jquery

I have XML like below

<parent id="parent">
    <body>
          body text<body>hello</body>
    </body>
</parent>

as shown in above code it have parent tag where there is only body tag should available, but there is some text in body tag with tag again. so if i use

$('#parent').find('body').text();

it show output as

body text hello

but i want the output exactly like

body text<body>hello</body>

how should i do? If again there are more than one body tag are written in first body tag it should be treated as only text. not as tag.

Upvotes: 0

Views: 108

Answers (4)

iovis
iovis

Reputation: 223

You can use some DOM Traversing:

$('#parent').find('body').first().html();

Upvotes: 0

Hamix
Hamix

Reputation: 1335

HTML

 <body>and another text followed by <div class="someText"></div>Some text followed by</body>

JQuery

var texts = $('.someText, body').map(function(){
    return this.previousSibling.nodeValue
});
alert(texts[0]); // "Some text followed by "
alert(texts[1]); // " and another text followed by "

DEMO

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

Use html instead:

$('#parent').find('> body').html();

Upvotes: 1

friedi
friedi

Reputation: 4360

$('#parent').find('body:first').html();

Upvotes: 1

Related Questions