T-Bone
T-Bone

Reputation: 25

Is there a generic method of accessing DOM elements without an id through Javascript?

I have a <p> tag without an id attribute that I'd like to remove. Would I be able to use a generic DOM string to access this element?

<html> 
    <body>
        <div>
            <p> // yada yada 
            </p>
        </div>
    </body>
</html>

In my instance I'm trying to remove the paragraph element with jQuery by:

$(function () {
    var remove = $(" /*Generic label goes here */ ").remove();
});

I thought it would be document.body.div.firstChild Is something like this possible?

Upvotes: 0

Views: 223

Answers (1)

Sgoettschkes
Sgoettschkes

Reputation: 13189

You can use normal css selectors within jQuery:

$(function () {
    var remove = $("body div p:first-child").remove();
});

If you just want top level divs inside body, use body > div p:first-child. if you only want p elements which are direct childs of body, use body > div > p:first-child.

Depending on what you need, you can also get all p elements and then iterate over them!

Upvotes: 4

Related Questions