oblac / jodd

Jodd! Lightweight. Java. Zero dependencies. Use what you like.
https://jodd.org
BSD 2-Clause "Simplified" License
4.06k stars 723 forks source link

Jerry create element error #69

Closed shking closed 10 years ago

shking commented 10 years ago
Jerry j = Jerry.jerry("<span></span>").attr("id", "test");
System.out.println(j.html());

Exception in thread "main" java.lang.NullPointerException
at jodd.lagarto.dom.Node.setAttribute(Node.java:443)
at jodd.jerry.Jerry.attr(Jerry.java:548)

Why?

igr commented 10 years ago

Its invalid usage ;) When you call:

Jerry j = Jerry.jerry("<span></span>")

this parses a string (document) and it is equal just to the document root. As in jQuery, you need first to select something in order to work with it! So you need to write the code like this:

Jerry j = Jerry.jerry("<span></span>");
j.$("span").attr("id", "test");

This will give you expected results.

This is an important difference between jQuery and Jerry. With jQuery you do not have a parsing process, since browsers parses everything for you. With Jerry you must have a parsing step and the first created Jerry is over the document node; so to start using parsing content you must start select something.

See more in our official documentation.

However, we should not throw NPE :) See 9573f5507029c75a7ff5fc4112ef4a38ecd948f3 for better error message.

igr commented 10 years ago

I've double check the logic, and all is fine, there is no need to change anything.

Just consider Jerry.jerry to be equal to $ in jQuery. So, as you can not say $.attr() you can not do the same thing in Jerry, too.

At the end, the set will not throw anything: 774a43b2d93af964a79e9ad78aecee9a44b2a18a.

Thank you!

shking commented 10 years ago

I solved the problem, thank you.