A NodeSet is a collection of Nokolexbor::Node objects returned by CSS or XPath queries. It includes the Enumerable module, allowing you to iterate over nodes, search for specific elements, and perform bulk operations on all nodes in the set.
Common Operations
- Iteration: Use
#each to iterate or #to_a to convert to an array. - Selection: Use
#first(n) to get the first n elements (or just the first if n is nil) and #last to get the final element. - Bulk Content Extraction:
#content (aliases: #text, #inner_text, #to_str): Returns the concatenated text content of all nodes.#inner_html: Returns the concatenated inner HTML of all nodes.#outer_html (aliases: #to_s, #to_html, #serialize): Returns the concatenated outer HTML of all nodes.
- Bulk Attribute Manipulation:
#attr(key, value = nil, &block) (aliases: #set, #attribute):- If
key is a Hash, it sets multiple attributes on all nodes. - If
key is a single value and value is provided, it sets that attribute on all nodes. - If
value is nil, it retrieves the attribute from the first node in the set. - Supports a block for dynamic value assignment.
#add_class(name) / #append_class(name): Adds a class to all nodes.#remove_class(name = nil): Removes a specific class from all nodes.#remove_attr(name) (alias: #remove_attribute): Removes a specific attribute from all nodes.
- Bulk DOM Modification:
#remove (alias: #unlink): Removes all nodes in the set from the document.#destroy: Destroys all nodes in the set.#wrap(node_or_tags): Wraps every node in the set with the specified node or tags.#add_class(name) / #append_class(name): Adds a class to all nodes.
Searching within a NodeSet
You can perform nested searches starting from the nodes within a NodeSet using:
#xpath(*args)#nokogiri_css(*args)
# Get an attribute from the first node in a NodeSet
value = node_set.attr("href")
# Set attributes on all nodes
node_set.attr("href" => "http://example.com", "class" => "a")
# Set attributes using a block
node_set.attr("href") { |node| "http://example.com" }
# Get concatenated text
text = node_set.text
# Get concatenated HTML
html = node_set.to_html