开发者

Jsoup: Optimal way of checking whether a <div> has an ID

开发者 https://www.devze.com 2023-02-18 01:18 出处:网络
I am able to iterate through all div elements in a document, using getElementsByTag(\"div\"). Now I want to build a list of only div elements that 开发者_如何学Gohave the attribute \"id\" (i.e. div e

I am able to iterate through all div elements in a document, using getElementsByTag("div").

Now I want to build a list of only div elements that 开发者_如何学Gohave the attribute "id" (i.e. div elements with attribute "class" shouldn't be in the list).

Intuitively, I was thinking of checking something like this:

  if (divElement.attr("id") != "")
    add_to_list(divElement);

Is my approach correct at all?

Is there a more optimal way of testing for having the "id" attribute? (the above uses string comparison for every element in the DOM document)


You can do it like this:

Elements divsWithId = doc.select("div[id]");
for(Element element : divsWithId){
    // do something
}

Reference:

  • JSoup > Selector Syntax


Try this:

var all_divs = document.getElementsByTagName("div");
var divs_with_id = [];

for (var i = 0; i < all_divs.length; i++)
  if (all_divs[i].hasAttribute("id"))
    divs_with_id.push(all_divs[i]);
0

精彩评论

暂无评论...
验证码 换一张
取 消