Noler Relon
Noler Relon

Reputation: 11

how to copy parent attributes in jquery?

I created an element and I want it to take attributes (especially the first "parent" class). Here's the code:

JQUERY:

$('.secondCategory>ul').prepend('<li class="afterclick"></li>');

HTML (how does it look like):

<li class="addGradient secondCategory">Lorem ipsum
    <ul class="sub-menu"><li class="afterclick">Lorem ipsum</li>
        <li id="itemsub1><a href="#">Lorem 1</a></li>
        <li id="itemsub2"><a href="#">Lorem 2</a></li>
    </ul>
</li>

I want the li "afterclick" I created to always read the first class (or all classes) of the first li element (<li class = "addGradient secondCategory">).

Upvotes: 0

Views: 63

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

If you always know the parent up-front (as you're doing $('.secondCategory>ul')) then you can get the class from that element using DOM methods:

var parentClass = $('.secondCategory')[0].className

then add it when you generate your html:

var parentClass = $('.secondCategory')[0].className

var html = '<li class="' + parentClass + ' afterclick">new element</li>'
$('.secondCategory>ul').prepend(html);
li { color: blue; }
li.addGradient { color: red; }
.afterclick { font-style:italic }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="addGradient secondCategory">Lorem ipsum
    <ul class="sub-menu">
        <li id="itemsub1"><a href="#">Lorem 1</a></li>
        <li id="itemsub2"><a href="#">Lorem 2</a></li>
    </ul>
</li>


If you specifically want it from the "parent", assuming you don't know what the parent will be, then you can keep a reference to the newly appended element and get the parent afterwards, eg:

var html = '<li class="afterclick">new element</li>'

var newElement = $(html).prependTo($('.secondCategory>ul'))

console.log(newElement.parent().parent()[0].className)
newElement.addClass(newElement.parent().parent()[0].className)
li { color: blue; }
li.addGradient { color: red; }
.afterclick { font-style:italic }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="addGradient secondCategory">Lorem ipsum
    <ul class="sub-menu">
        <li id="itemsub1"><a href="#">Lorem 1</a></li>
        <li id="itemsub2"><a href="#">Lorem 2</a></li>
    </ul>
</li>

In this case I've used .parent().parent() as you wanted the classes from the "closest" li.

Upvotes: 1

Related Questions