简体   繁体   中英

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM