I have a simple HTML snippet as follows:
<div class="out"><p class="a">This is a paragraph. <p class="b">another</p></p></div>
I need to add a new class b to the outer p element, resulting in the following expected result:
<div class="out"><p class="a b">This is a paragraph. <p class="b">another</p></p></div>
The inner p element should remain the same.
Is this possible?
Find the right element and change its attribute using setAttribute method.
The code below uses requirements clarified in a comment: the paragraph of interest is the first one below a
div, and its attributeclassneed be appended if it exists, or created.This still assumes that the
pdoesn't have sibling paragraphs (so directly under the samediv), or if it does that they should be changed in the same way as well. If that's not the case then one should identify all those siblings and skip them.The search is first for
pand then the node is checked for its parent, in case some subtle refinements creep in ("Yes, apunder adiv, but except for the edge case of ..."). But if that's not a concern and it is strictly thepunder adivthen better go for that directlyThen append to the
classattribute or create it the same way as above.The above prints