Kiddo
Kiddo

Reputation: 943

Get text from selector in jquery - wordpress

I want to take the text of first row from body in wordpress and I have some problems.

My code: HTML CODE

<body id='asd'>
   <h2>Text1</h2>
   <p>Text2</p>
   <b>Text3</b>
</body>

JS CODE:

console.log(jQuery('#asd').children(':first').text());

This code is working locally. It will output in console, exactly what I need: Text1, but, in wordpress doesn't work.

If I try the same code on wordpress, no output is show.

If i try:

console.log(jQuery('#asd').children(':first'));

On local output is: [h2, prevObject: r.fn.init(1)] On wordpress output is: [selector: "", prevObject: a.fn.init, context: document]

Can someone help?

Upvotes: 0

Views: 469

Answers (3)

Pete
Pete

Reputation: 58442

From your comments, it looks as if the body is in a separate iframe that is within the main document. To target an iframe's contents you need to do the following:

$('#iframe-id').contents().find('#asd').children(':first').text()

Upvotes: 1

Malay Solanki
Malay Solanki

Reputation: 110

I think you need to put code in jQuery document ready event. Your code may execute before body tag loaded in DOM.

Upvotes: 0

Ahmed Ginani
Ahmed Ginani

Reputation: 6650

Just use the following

jQuery(document).ready(function(){
    jQuery('#asd:first-child').text();
}

It will return the first children tag value.

Upvotes: 0

Related Questions