tags:

views:

40

answers:

2

how to read contents from $(this) selector and its children separately?

    <div class="para">
      <h1 class="hd">heading 1</h1>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tincidunt pharetra         est, quis facilisis purus elementum ut. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
    </div>

I can read the contents of the <h1>separately using $(this).children("h1").text() but how do you read the content from the excluding <h1>?

thanks

A: 
$(this).find(:not(h1)).text();

Where you take this and then find anything in it which is not an h1.

Edit: Sorry, val() was incorrect needed to be text per comment, thanks.

Chris
`val()` only works on input elements. You mean `text()` ?
Felix Kling
This finds all descendant elements that aren't `<h1>`, but you need quotes, so `":not(h1)"` since `.find()` takes a string. But, jQuery doesn't select text elements like this, so you'd still get am empty string every time :)
Nick Craver
A: 

You can get the content via a .clone(), like this:

$(this).clone().children("h1").remove().end().text() 

You can give it a try here, all we're doing is cloning the element, removing that <h1> from the clone then getting the text out.

Nick Craver
dude u r a life saver
manraj82
Is this answer any better then my suggestion? I am not that great at javascript and curious why you chose this approach ?
Chris
@Chris - There are a few issues with your version, I'll comment on your answer.
Nick Craver
alas, it just seems you should be able to do that without the clone :(
Mark Schultheiss
@Mark - You could do something like `$(this).contents()[2].nodeValue` but it's a bit more brittle, or a loop through text nodes to find a non-empty one, not sure what's most optimal here, depends on the programmer I suppose?
Nick Craver
@Nick yes, kind of what I was considering but still did not give me that "clean" feeling :) - I have often seen questions about getting the text "not" within a child element of an element so it seems to bring to pause a lot of users.
Mark Schultheiss