I have a lot of divs identical to the one below
<div class="example">
Some of these divs have child nodes, which look something like this
<input type="submit" name="auto-gen" value="Extra" id="auto-gen" class="add-button" aria-label="" data-active="True" data-isfirstcontrol="False" type="button">
Due to working with legacy software, I can’t change anything about the structure of these divs (can’t change id’s or change class name or anything). However, I want to be able to add some CSS (float: right;) to the example class, but only if they have a child with the "add-button" class.
I’ve been trying to do stuff like below:
$('.add-button').parent().style.styleFloat = 'right'
However, whatever I try I get the following error message
Uncaught TypeError: Cannot set properties of undefined (setting 'styleFloat').
Anyone have any ideas?
>Solution :
If there are no .add-button
elements which parent()
is not a .example
, you can just target every add-button
and style his parent()
Using jquery
$(".add-button").parent().css({ float: "right" });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
</div>
<div class="example">
<input type="submit" name="auto-gen" value="Extra" id="auto-gen" class="add-button" aria-label="" data-active="True" data-isfirstcontrol="False" type="button">
</div>
Using plain javascript
You might not need Jquery
document.querySelectorAll('.add-button').forEach(e => e.parentNode.style.float = 'right')
<div class="example">
</div>
<div class="example">
<input type="submit" name="auto-gen" value="Extra" id="auto-gen" class="add-button" aria-label="" data-active="True" data-isfirstcontrol="False" type="button">
</div>