Alan2
Alan2

Reputation: 24572

How can I find if an element has an h1 element inside it?

I have the following:

$('#content')

What I would like is to check if this has an h1 element inside of it. If it has then I would like to do the following:

$('#content').buildTableOfContent();

Is there a way I could do this check using jQuery?

Upvotes: 0

Views: 906

Answers (3)

user663031
user663031

Reputation:

If you are not fixated on jQuery, this is just

if (document.getElementById("content").getElementsByTagName("H1")[0]) {
    ...build TOC...
}

Upvotes: 0

bjornd
bjornd

Reputation: 22941

It could be done in just one line thank to rich jQuery API:

$('#content:has(h1)').buildTableOfContent();

Upvotes: 1

VisioN
VisioN

Reputation: 145438

Something like that should work:

if ($("#content h1").length > 0) {
    $("#content").buildTableOfContent();
}

Upvotes: 3

Related Questions