user

Mohamed Atef

27 Jan 2022

How to get the style of element in jQuery? add it to another

jQuery

Hello everyone, I am wondering How can I get a style attr of a specific element using jQuery and add it to another div? for example if I have element like 

<div class="posts-container" style="display: block; background-color: #f7f8f1">...</div>

How can I add the same style to another div with class posts-container-custom?
Thanks.

Comments

Joseph Morgan

27 Jan 2022

Best Answer

best answer

Hi Mo, you can achieve what you need using this code to get the style attribute 

var existsStyle = jQuery("div.posts-container").attr('style');
console.log(existsStyle);

then you can add the style to the second div using 

jQuery("div.posts-container-custom").attr("style", existsStyle);

so the entire code should looks like 

var existsStyle = jQuery("div.posts-container").attr('style');
console.log(existsStyle);
jQuery("div.posts-container-custom").attr("style", existsStyle);

Good luck

Replies

Mohamed Atef

27 Jan 2022

githubgithubgithub

Thank you Joseph, this logic makes sense & worked for me 

© 2024 Copyrights reserved for web-brackets.com